I have a LinearLayout which I've looped a number of new Button objects into. How do I go about clearing that div correctly (eg removing all the buttons)? I've tried a number of times (unsuccessfully) to do this, but have nothing to show for it.
** edit **
I'm not sure if this helps, but in flex/AS3 I would do something like:
while(myView.numChildren) myView.removeChildAt(0);
** a little code **
View col1 = findViewById(R.id.col1);
for(final Map.Entry<String,HashMap<String,String>> entry : _nav.entrySet()) {
Button item = new Button(this);
item.setText(entry.getKey());
item.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
openCol2(entry);
}
});
((LinearLayout) col1).addView(item);
}
private final void openCol2(Map.Entry<String,HashMap<String,String>> entry) {
View col2 = findViewById(R.id.col2);
// here is where I want to clean out col2. Right before I add more buttons.
for(int i = 0; i < _nav.size(); ++i) {
Button item = new Button(this);
//item.setText(entry.getKey());
((LinearLayout) col2).addView(item);
}
}
Try this
LinearLayout col2 = (LinearLayout)findViewById(R.id.col2);
col2.removeAllViews();
Assumption: R.id.col2 is of LinearLayout type else to make it more generic typecast it to ViewGroup. Hope this help!!!
Related
I have a LinearLayout and adding dynamic checkboxes to it.
String status = intent.getStringExtra("status");
String content = intent.getStringExtra("content");
String[] statusSplit = status.split("\n");
String[] contentSplit = content.split("\n");
for (int i = 0; i < contentSplit.length; i++) {
CheckBox checkBox = new CheckBox(this);
boolean st;
if(statusSplit[i].equals("1"))
st=true;
else
st=false;
checkBox.setId(i);
checkBox.setTextSize(20);
checkBox.setText(contentSplit[i]);
checkBox.setChecked(st);
linearLayout.addView(checkBox);
// checkBox.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener);
}
This works fine, but hereafter I don't know how to retrieve views again, because I want to be able to change the CheckBoxes text and values. I want to get and edit LinearLayout views again, because I want to check or uncheck a checkbox or edit the checkbox text in case of updating the items.
I use some code like this:
switch (item.getItemId()){
case R.id.edit:
for(int i = 0; i<linearLayout.getChildCount(); i++){
View view = linearLayout.getChildAt(i);
CheckBox checkBox = view.findViewById(R.id.check_box);
checkBox.setText("new text");
view.setBackgroundColor(getResources().getColor(R.color.white));
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
case R.id.save:
// update checkboxes texts and values, then pass them to database.
}
Appreciate any help.
Could you please identify what i have done wrong in my code , as i am newbie to android and help ill be appreciated, please let me know if you required more info.
Actually i am working on dynamic Radio group creation and though on view pager using fragments like tabular/swiping layouts
What all i have tried for clearing radio Group/ radio Button
i have tried radioGroup.clearCheck(); but in this case i have faced a looping issue so i just skipped this and thought to unchecked all buttons of my current radio group which is in listener but while doing this i am facing very unpredictive behavior, like some time i am not able to check another boton or can check two buttons
Note what i am trying : just i have changed something, what i want that, there are set of buttons i n radio group, and while i clicked on one button it is checked , but i clicked on another button of same radio group then previously checked button is not getting unchecked and even new buttons gets checked, so what i have done is that while is checked is call and code comes to my listener there i am checking if button is already checked then io am trying to unchecked same , so is there any docs or something by which i can learn to create big amount of radio group dynamically and handle those. i believe that because i am creating buttons dynamically i am facing this issue
private void checkOnClickedRadioGroupCalled(ArrayList<LinearLayout> setRadioGroupValuesLinearLayoutList) {
for (final LinearLayout linearLayoutGroup : setRadioGroupValuesLinearLayoutList) {
String linearLayoutTag = linearLayoutGroup.getTag() + Constant._RADIOGROUP;
System.out.println("Radio group tag name : - " + linearLayoutTag);
RadioGroup radioGroup = (RadioGroup) v.findViewWithTag(linearLayoutTag);
if (radioGroup == null) {
radioGroup = (RadioGroup) getRadioInitialize(linearLayoutTag);
}
if (radioGroup != null) {
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
listOfRadioButtons = new ArrayList<RadioButton>();
DynamicFieldUpdate.getButtonsCountAndInit(group,listOfRadioButtons);
RadioButton radioButtonInSideClickListner = (RadioButton) group.findViewById(checkedId);
/*RadioButton mButton = (RadioButton) group.getChildAt(0);
RadioButton mButton1 = (RadioButton) group.getChildAt(1);*/
if(radioButtonInSideClickListner!=null && radioButtonInSideClickListner.isChecked()) {
/*mButton.setChecked(false);
mButton1.setChecked(false);*/
for(int i = 0;i<listOfRadioButtons.size();i++){
if(radioButtonInSideClickListner.getId() == getViewId(listOfRadioButtons.get(i))) {
radioButtonInSideClickListner.setText(listOfRadioButtons.get(i).getText());
radioButtonInSideClickListner.setChecked(true);
} else{
radioButtonInSideClickListner.setText(radioButtonInSideClickListner.getText());
radioButtonInSideClickListner.setChecked(false);
}
}
}
addRadioGroupValuesViewListInputValue.add(group);
}
});
}
}
}
here is my code for creating radio group
public static void setCustomRadioGroup(LinearLayout layout, Context context, ArrayList<String> setName, ArrayList<View> viewList) {
int sizeOfList = setName.size();
final RadioButton[] radioButtons = new RadioButton[setName.size()];
RadioGroup radioGroup = new RadioGroup(context);
System.out.println(layout.getTag()+"_RadioGroup"+" this is tag from dynamic layout creation");
//set this in constant afterweard while dry run
radioGroup.setTag(layout.getTag()+"_RadioGroup");
// /* LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
// LinearLayout.LayoutParams.MATCH_PARENT,
// LinearLayout.LayoutParams.WRAP_CONTENT
// );
// layout.addView(radioGroup, params);*/
//radioGroup.setTag();//create the RadioGroup
if (setName.size() < 3) {
radioGroup.setOrientation(RadioGroup.HORIZONTAL);
} else {
radioGroup.setOrientation(RadioGroup.VERTICAL);
}
//or RadioGroup.VERTICAL
for (int i = 0; i < setName.size(); i++) {
radioButtons[i] = new RadioButton(context);
radioButtons[i].setText(setName.get(i));
String id = layout.getTag()+setName.get(i);
radioButtons[i].setId(id.hashCode());
Log.v("Selected", "New radio item id in Dynamic fiels: " + id.hashCode());
radioGroup.addView(radioButtons[i]);
}
layout.addView(radioGroup);
viewList.add(radioGroup);
}
I have this code :
private ImageView d1;
private ArrayList<Integer> listaImagenes = new ArrayList<Integer>();
private ArrayList<String> listaFrases = new ArrayList<String>();
private Button button;
private Integer contador = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.rellenarImagenes();
setContentView(R.layout.imagentonas);
d1 = (ImageView) findViewById(R.id.imagenes01);
while (contador < listaImagenes.size()) {
d1.setImageResource(listaImagenes.get(contador));
button = (Button) findViewById(R.id.botoncillo);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
contador++;
}
});
}
}
private void rellenarImagenes() {
listaImagenes.add(R.drawable.a01);
listaImagenes.add(R.drawable.a02);
listaImagenes.add(R.drawable.a03)
}
I am trying do a loop that when I press the button , increment contador and d1 change image.
but it is not working, application background remains black and not working.
remove while loop and setimage in onclick method.
You are expecting that modifying the value of the variable contador would result in the array item to change.
Keep in mind that in the code line d1.setImageResource(listaImagenes.get(contador));, the get function receives an int. So at the time where it's called it receives a value, not a reference to an Integer. When you change the value of contador, the value that was used to obtain the index in the array is not changed.
And even if the value did change, d1 would still be using the same resource.
What you need to do in the onClickListener is add the code to set the image. Something along the lines of
public void onClick(View v) {
++contador;
if (contador >= listaImagenes.size())
{
contador=0;
}
//you'll probably need to modify the next line to be able to access the button variable.
//one way to do it is to use a final variable in the onCreate method that creates this OnClickListener
button.setImageResource(listaImagenes.get(contador));
}
The while loop is not needed. What your code is doing is setting the image to the 3 items of the array, one after the other, and adding a new click listener 3 times.
I will try to answer and point some of the flaws you have in the code.
wat if there were 100 drawable like R01 ,R02...? Instead you can use getting drawable using string.
why are you using while loop ? since you have the counter you can directly use that.
Let me try to write the code
int contador=1;
#Override
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.imagentonas);
context=this;
d1=(ImageView)findViewById(R.id.imagenes01);
button=(Button)findViewById(R.id.botoncillo);
button=(Button)findViewById(R.id.botoncillo);
button.setOnClickListener( new View . OnClickListener () {
public void onClick ( View v ) {
int id = context.getResources().getIdentifier("a"+contador,
"drawable", context.getPackageName());
d1.setImageResource(id);
contador++;
}
});
}
Notice : int id = context.getResources().getIdentifier("a"+contador,"drawable", context.getPackageName()); Here using the string you can access the drawable this solves the issue for any number of consecutive drawables.
Hope you get the concept...
Thanks
Look at following android code. IMGS is a 2 dimensional array of ImageView. I am adding onClickListener to it in a for loop. How to identify which view has been clicked ? I dont want to iterate over all the 36 elements using view.getId();.
private static final Integer[] Icons = {
R.drawable.r,
R.drawable.re,
R.drawable.u,
R.drawable.et,
R.drawable.w,
R.drawable.ya
};
private ImageView[][] IMGS= new ImageView[6][6];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IMGS[0][0] = (ImageView) findViewById(R.id.immg11);
for (int i=0; i < 6; i++)
{
for (int j=0; j<6; j++)
{
Drawable d = getResources().getDrawable(Icons[i]);
IMGS[i][j].setImageDrawable(d);
IMGS[i][j].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//HOW TO KNOW WHICH VIEW HAS BEEN CLICKED ?
}
});
}
}
}
Notice the View argument passed to onClick(View v)? It's the view that was clicked.
You can call v.getId() to retrieve its id.
Agreed, but there are 36 elements over which i have to iterate if I use this method. Is there a way to know the indexes of clicked IMGS ?
You can use setTag() to save whatever data you want in each view and retrieve it later with getTag().
I have a working application but want to optimise the code. Below is one example where I create 10 separate imagebuttons (note the incrementing objectname and XML reference for each) and set their listeners. Can anyone suggest a more optimal way of doing this, perhaps in a dynamic method/loop please? Thanks....
private void initialiseButtons() {
ImageButton imageButton1 = (ImageButton)this.findViewById(R.id.imageButton1);
imageButton1.setOnClickListener(this);
ImageButton imageButton2 = (ImageButton)this.findViewById(R.id.imageButton2);
imageButton2.setOnClickListener(this);
ImageButton imageButton3 = (ImageButton)this.findViewById(R.id.imageButton3);
imageButton3.setOnClickListener(this);
ImageButton imageButton4 = (ImageButton)this.findViewById(R.id.imageButton4);
imageButton4.setOnClickListener(this);
ImageButton imageButton5 = (ImageButton)this.findViewById(R.id.imageButton5);
imageButton5.setOnClickListener(this);
ImageButton imageButton6 = (ImageButton)this.findViewById(R.id.imageButton6);
imageButton6.setOnClickListener(this);
ImageButton imageButton7 = (ImageButton)this.findViewById(R.id.imageButton7);
imageButton7.setOnClickListener(this);
ImageButton imageButton8 = (ImageButton)this.findViewById(R.id.imageButton8);
imageButton8.setOnClickListener(this);
ImageButton imageButton9 = (ImageButton)this.findViewById(R.id.imageButton9);
imageButton9.setOnClickListener(this);
ImageButton imageButton0 = (ImageButton)this.findViewById(R.id.imageButton0);
imageButton0.setOnClickListener(this);
}
You could use a loop and use getIdentifier() method.
int idToInitialize;
ImageButton ib;
for (int i = 0; i < 9; i++) {
idToInitialize = getResources().getIdentifier("imageButton" + i, "id", getPackageName());
ib = (ImageButton) this.findViewById(idToInitialize);
ib.setOnClickListener(this);
}
Hovewer, it is very slow if we compare to the normal method.
You can reduce the boilerplate code by using http://androidannotations.org/ which will allow you to do someting like that
#ViewById
ImageButton imageButton1;
but it would be perhaps better to use an array or a list of buttons rather than multiple references, something like that for example :
private void init() {
int[] ids=new int[]{R.id.imageButton1, R.id.imageButton2 ...};
List<ImageButton> buttons=new ArrayList<ImageButton>;
for(int id : ids) {
buttons.add((ImageButton)this.findViewById(id));
}
}
you can then easily iterate on the List, for example to set the listener
for(ImageButton button : buttons) {
button.setOnClickListener(this);
}
You can use arrays, lists ...
For example:
private static final int[] BUTTONS_IDS = new int[] {R.id.imageButton0, R.id.imageButton1, R.id.imageButton2, R.id.imageButton3, R.id.imageButton4, R.id.imageButton5, R.id.imageButton6, R.id.imageButton7, R.id.imageButton8, R.id.imageButton9};
ImageButton[] buttons = new ImageButton[BUTTON_IDS.length];
private void initialiseButtons() {
for (int i = 0; i < BUTTONS_IDS.length; i++) {
buttons[i] = (ImageButton) findViewById(BUTTONS_IDS[i]);
buttons[i].setOnClickListener(this);
}
}
You can also put the list of ids in the arrays.xml file.
I can't try it cause I have no Android Environmetn here. But I think this should work:
private void initialiseButtons() {
for(int i = 0; i < 10; i++) {
ImageButton imageButton = (ImageButton)this.findViewById(R.id.getClass().
getField("imageButton" + i).get(R.id));
imageButton.setOnClickListener(this);
}
}
If it's only for setting the onClickListener, you can get rid off your whole initialiseButtons() methods and simply add android:onClick="handleButtonClick" in your layout xml and define that method in your activity like so:
public void handleButtonClick(View view) {
switch(view.getId()) {
case R.id.imageButton1: // handle button 1 pressed ....
case R.id.imageButton2: // handle button 2 pressed ....
// ... handle further buttons
}
}