Android Button Id

If I created a button in xml and I want to use this button several times, but give them a unique identifier, how to do it? I don’t know how many buttons I will have, so I can’t create multiple buttons in my XML file. I want to be able to change the identifier of buttons during program startup. I tried to make button.setId (), but then everything breaks and does not work.

+3
source share
4 answers

You can make an independent button.xml file (or even make it like a style) and then inflate it in your code as needed.

, , , , . , , , , xml for.

LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);  
String[] countries = {"US", "Canada", "UK", "Australia"};
String country;
// Don't forget to add the following layout to your xml. 
LinearLayout buttonLayout = (LinearLayout) findViewById(R.id.buttonLayout);  
buttonLayout.removeAllViews();
for (int i = 0; i < countries.length(); i++) {
    country = countries.getString(i);
    Button temp = (Button)inflater.inflate(R.layout.button);
    // Don't forget that id is an int, not a string.
    button.setId(id);
    button.setText(country);
    buttonLayout.addView(temp);
}

: XML include :

<include layout="@layout/button" 
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button 1"
/>
+2

, , .

Button button = new Button();
// init it here

layout.add(button, new LayoutParams(...));
+1

enter id in xml e.g.

<Button android:id="@+id/close"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:text="@string/title_close" />
0
source

If you are not sure which instances you need in your application for a particular widget, go for dynamic creation. XML is mainly intended for static creation.

0
source

All Articles