Cast Class object to EditText in Android? - java

public void changeCurrency(RelativeLayout layout) {
for (int i = 0; i < layout.getChildCount(); i++) {
View v = layout.getChildAt(i);
Class c = v.getClass();
if (c == EditText.class) {
// validate EditClass
} else if (c == TextView.class) {
//validate RadioButton
}
}
}
In the above code I'm trying to iterate through gui elements in a layout and validate their contents. I'm struggling at the commented parts.
I.e. getting access to the EditText's text value..
I can't figure out how to cast the c object to a EditText to check the values.
Ideas?

Try using the logic below
View v = layout.getChildAt(i);
if (v instanceof EditText) {
EditText et = (EditText) v;
//Do stuff
} else if (v instanceof TextView) {
//Do other stuff
}
Since EditText is a subclass of TextView, you need to check for EditText first. An EditText will test positive as an instance of TextView.

Most of the views that use text extend from TextView. This should be sufficient if all you are doing is validating text.
public void changeCurrency(RelativeLayout layout) {
for (int i = 0; i < layout.getChildCount(); i++) {
View v = layout.getChildAt(i);
if (v instanceof TextView) {
TextView t = (TextView) v;
String text = t.getText().toString();
// ...
}
}
}

Related

Set text color of all elements in Activity

Is there a way to change the complete textColor of every element(Checkboxes,RadioButtons,etc..) in a activity ?
CheckBox check = (CheckBox)findViewById(R.id.checkBox);
check.setTextColor(Color.rgb(Rot,Gruen,Blau));
this is how i change the color of the checkbox but i want change all the elements, is it possible?
Hope it may help to solve your problem.
private void setAppFontColor(ViewGroup mContainer, int color) {
if (mContainer == null || color == 0)
return;
final int mCount = mContainer.getChildCount();
for (int i = 0; i < mCount; ++i) {
final View mChild = mContainer.getChildAt(i);
if (mChild instanceof TextView) {
((TextView) mChild).setTextColor(color);
} else if (mChild instanceof Button) {
((Button) mChild).setTextColor(color);
} else if (mChild instanceof ViewGroup) {
setAppFontColor((ViewGroup) mChild, color);
}
}
}
Where
ViewGroup mContainer = (ViewGroup) findViewById(android.R.id.content).getRootView();
yes,add textColorSecondary to your activity theme
<item name="android:textColorSecondary">yourcolor</item>

Best solution for Checkbox in LinearLayout

In my LinearLayout, there's a variable number of CheckBoxes. In a question I had a month ago someone said it´s better to add checkboxes dynamicly instead of make them not visible.
Integer[] count = new Integer[]{1,2,3,4,5,6,7,8,9,10};
size = mFrageList.get(position).getAuswahlList().size();
for (int i = 0; i < size; i++) {
cBox = new CheckBox(this);
cBox.setText(mFrageList.get(position).getAuswahlList().get(i));
cBox.setId(count[i]);
cBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
antwortencode[position] += "" + buttonView.getId();
frageBeantworten.setText("Antwort :"+antwortencode[position]+" abgeben");
} else {
String id = Integer.toString(buttonView.getId());
antwortencode[position] = antwortencode[position].replaceAll(id,"");
if(!antwortencode[position].isEmpty() || antwortencode[position]!= "") {
frageBeantworten.setText("Antwort :" + antwortencode[position] + " abgeben");
} else {
frageBeantworten.setText("Keine Checkbox(en) gewählt");
}
}
}
});
antworten.addView(cBox);
Currently, I'm able to save a string with the checked checkboxes, if I un-check a checkbox, it deletes it's value out of the string.
If I update the activity, the string is saved, and the checkboxes get a new List from the mFrageList.get(position)getAuswahlList(); and fill a new string in the "antwortencode" List with their values.
If I go back to the last position, I have the string which was generated but the checkboxes aren't checked anymore. But they have the Strings from the old position. that means everything is saved except the state of the checkboxes. I cant set a cBox.setChecked(isChecked) or buttonView.setChecked(isChecked) or buttonView.setChecked(buttonView.isChecked()) or something which is nearly the same in syntax.
I don't know what I can do besides declaring 10 Checkboxes in a xml file to talk to them one by one and set the VISIBLE.false if the auswahlList.get(position).isEmpty().
IMPORTANT: My XML is a Scrollable Activity because the size of the content overextended the screen. Thats why i didn´t and can´t use a Listview. So i need a solution that uses a LinearLayout
The truth is, you should actually use a ListView. As long as you reuse a layout multiple times - do it.
There are 2 options:
ListView as root - add other contents of your layout as different types of view
ListView inside a scrollable layout - there are many lightweight implementations of ListView that allow it to wrap content, e.g. https://github.com/paolorotolo/ExpandableHeightListView
The other thing is how to maintain the state of Checkboxes - use model classes. It's extremely easy with a ListView as it forces you to use an Adapter which provides methods to iterate over all positions.
Example of an adapter:
public class CheckableItemAdapter extends BaseAdapter {
private List<Pair<Integer, Boolean>> items = new ArrayList<>();
public void setItems(List<Pair<Integer, Boolean>> items) {
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
ViewHolder holder;
if (convertView == null) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_checkable, parent, false);
holder = new ViewHolder(view);
view.setTag(holder);
} else {
view = convertView;
holder = (ViewHolder) view.getTag();
}
Pair<Integer, Boolean> item = items.get(position);
holder.itemCheck.setChecked(item.second);
return view;
}
static class ViewHolder {
CheckBox itemCheck;
public ViewHolder(View itemView) {
itemCheck = (CheckBox) itemView.findViewById(R.id.check);
}
}
}
I´ve managed to solve my problem alone, and now i want to share it, even if it isn´t the best example of programming.
Integer[] count = new Integer[]{1,2,3,4,5,6,7,8,9,10}; //maximum of 10 Checkboxes
size = mFrageList.get(position).getAuswahlList().size();
for (int i = 0; i < size; i++) {
cBox = new CheckBox(this);
cBox.setText(mFrageList.get(position).getAuswahlList().get(i));
cBox.setId(count[i]);
try{ //this is where the magic happens
if(antwortencode[position] != ""){ //cause i won´t want null in my db i´ve set "" as standard string in my activity for the List<String>
String code = antwortencode[position];
char[] c = code.toCharArray();
for(int j=0;j<=c.length;j++){
int x = c[j] -'0'; // 'char 1' - 'char 0' = Integer 1 , lol
if(cBox.getId()== x){ //compare them
cBox.toggle(); //if it fits, toggle
}
}
}
} catch (Exception e){
e.printStackTrace();
} //and here it ends
cBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
antwortencode[position] += "" + buttonView.getId();
frageBeantworten.setText("Antwort :"+antwortencode[position]+" abgeben");
} else {
String id = Integer.toString(buttonView.getId());
antwortencode[position] = antwortencode[position].replaceAll(id,"");
if(!antwortencode[position].isEmpty() || antwortencode[position]!= "") {
frageBeantworten.setText("Antwort :" + antwortencode[position] + " abgeben");
} else {
frageBeantworten.setText("Keine Checkbox(en) gewählt");
}
}
}
});
antworten.addView(cBox);
Ty for the answers and for the correction of my question.
Nostramärus

Get button from view

I am trying to return a button object from a view to subsequently run setText against.
I am having trouble converting it though.
Any advice appreciated.
public Button aiPlayerPick() {
Button btn = null;
TableLayout tableLayout = (TableLayout) findViewById(R.id.tableLayout);
for (int rowIndex = 0; rowIndex < tableLayout.getChildCount(); rowIndex++) {
View tableLayoutChild = tableLayout.getChildAt(rowIndex);
if (tableLayoutChild instanceof TableRow) {
for (int i = 0; i < ((ViewGroup) tableLayoutChild).getChildCount(); i++) {
View view = ((ViewGroup) tableLayoutChild).getChildAt(i);
if (view instanceof Button && view.getTag() == aiPickedButton) {
View btn_v = view.findViewWithTag(aiPickedButton);
System.out.println("Button: " + btn_v);
btn = (Button) findViewById(R.id.btn_v); // Problem is here, I can't get that view to be seen as a button
break;
} else {
i++;
}
}
}
}
return btn;
}
You've already retrieved the View (parent of the Button) to your code with:
View btn_v = view.findViewWithTag(aiPickedButton);
So the only thing you need to do is cast it to be a Button with btn = (Button) someView. Your code would look like:
View btn_v = view.findViewWithTag(aiPickedButton);
System.out.println("Button: " + btn_v);
btn = (Button) btn_v;
System.out.println("Button: " + btn);

ANDROID: clicking multiple checkboxes

I want to show the name of those multiple checkboxes that was checked. The problem is that when I check on any of them, only the last one checked is written on the textview. How can I resolve this?
I don't really understand how I will concatenate the names of those checkboxes.
public void ChkCommand(View v)
{
txtans = (EditText)findViewById(R.id.txtcon1);
if(v.getId() == R.id.chk1 && ((CheckBox)v).isChecked()){
chkClick = (CheckBox) findViewById(R.id.chk1);
}
else if(v.getId() == R.id.chk2 && ((CheckBox)v).isChecked()){
chkClick = (CheckBox) findViewById(R.id.chk2);
}
else if(v.getId() == R.id.chk3 && ((CheckBox)v).isChecked()){
chkClick = (CheckBox) findViewById(R.id.chk3);
}
String value = chkClick.getText().toString();
txtans.setText(value);
}
public void CloseConF(View v)
{
Intent intent = new Intent(this, SampComponents.class);
startActivity(intent);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.con_chk_samp, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_con_chk_samp,
container, false);
return rootView;
}
}
}
Each time you want to display the state of all your three checkboxes, you have to check all three:
String value = "";
if (((CheckBox) findViewById(R.id.chk1)).isChecked()) {
value += (CheckBox) findViewById(R.id.chk1).getText().toString();
}
if (((CheckBox) findViewById(R.id.chk2)).isChecked()) {
value += (CheckBox) findViewById(R.id.chk2).getText().toString();
}
if (((CheckBox) findViewById(R.id.chk3)).isChecked()) {
value += (CheckBox) findViewById(R.id.chk3).getText().toString();
}
txtans = (EditText)findViewById(R.id.txtcon1);
txtans.setText(value);
Then of course there would be some refactoring to do to get something cleaner, but that should get you started.
Try getting the checkbox text in every if else and append to a string value like this. chkBox1, chkBox2 and chkBox3 will be CheckBoxes in your java class.
public void ChkCommand(View v)
{
String value="";
txtans = (EditText)findViewById(R.id.txtcon1);
if(chkBox1.isChecked())
{
/*((CheckBox) findViewById(R.id.chk3)).setChecked(false);
((CheckBox) findViewById(R.id.chk2)).setChecked(false);*/
chkClick = (CheckBox) findViewById(R.id.chk1);
value += chkClick.getText().toString()+", ";
}
if(chkBox2.isChecked())
{
/*((CheckBox) findViewById(R.id.chk1)).setChecked(false);
((CheckBox) findViewById(R.id.chk3)).setChecked(false);*/
chkClick = (CheckBox) findViewById(R.id.chk2);
value += chkClick.getText().toString()+", ";
}
if(chkBox3.isChecked())
{/*
((CheckBox) findViewById(R.id.chk1)).setChecked(false);
((CheckBox) findViewById(R.id.chk2)).setChecked(false);*/
chkClick = (CheckBox) findViewById(R.id.chk3);
value += chkClick.getText().toString();
}
txtans.setText(value);
}
So you will get the result with all checked checkboxes' text. Hope this helps.
P.S: I just realized from #njzk2 's comment that you will need to changed else if to if in order to get all checkboxes's state.
Make value a field
private String value = "";
then change
String value = chkClick.getText().toString();
to something as:
value = value + " / " + chkClick.getText().toString();
But it's also necessary to tweak a bit the logic for reading the status from the checkboxes, otherwise they will add text also while un-checking.
Declare StringBuffer or StringBuilder member variables
StringBuffer buff = new StringBuffer();
Try this
buff.append(chkClick.getText().toString()+" ");
txtans.setText(buff.toString());
in place of
String value = chkClick.getText().toString();
txtans.setText(value);
It should work if your checkbox checking action is working correctly

EditText array FocusChange

I have 80 EditText fields (cube[i]) and want to read what is in inside the text fields when the text field loses focus.
I can detect when any of the EditTexts (cube) loses focus but I cannot detect exactly which one, Im trying to find which cube is focused on.
the line "EditText cube = (EditText) v.getClass();" is giving me an error
Maybe I can use the View v?
for (int i = 0; i < cube.length; i++) {
cube[i].setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
EditText cube = (EditText) v.getClass();
String s = cube.getText().toString();
//cubecolor();
}
}
});
}
}
Any help is appreciated.
while creating set some tag to the editText like this (pseudo code)
EditText edit = new EditText(context);
edit.setTag(Integer.valueOf(i)); // i is within the for loop;
Now during the onFocus get the tag
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
EditText cube = (EditText) v;
Integer tag = (Integer)cube.getTag();
//code to sort out which cube based on tag
String s = cube.getText().toString();
//cubecolor();
}
}
This worked, Thanks Dante.
for (int i = 0; i < cube.length; i++) {
cube[i].setTag(Integer.valueOf(i)); // give cubes tags
}
for (int i = 0; i < cube.length; i++) {
cube[i].setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
Integer tag = (Integer) v.getTag();
String s = cube[tag].getText().toString();
Log(TAG, " Content" + s);
revert_cubecolor(tag);
}
}
});
}

Categories

Resources