How to set id of dynamically created layout?

I want to give an identifier to some views (textview, imageview, etc.) in a layout that is programmatically created. So the best way to set ID.

+59
android
Jan 20 2018-12-12T00:
source share
10 answers

You create the ids.xml file and put in it all the necessary identifiers, as shown below.

<?xml version="1.0" encoding="utf-8"?> <resources> <item type="id" name="layout1" /> <item type="id" name="layout2" /> <item type="id" name="layout3" /> </resources> 

Now for your dynamically created layouts or views you can use these identifiers below

 new_layout1.setId(R.id.layout1); new_view2.setId(R.id.layout2); new_layout3.setId(R.id.layout3); 

I hope this can help you.

+107
Jan 20 '12 at 6:15
source share

Google finally realized the need to create unique identifiers for programmatically generated views ...

From API level 17 and above, you can call View.generateViewId () once

+34
Feb 22 '16 at 10:29
source share

create the res/values/ids.xml and

 <?xml version="1.0" encoding="utf-8"?> <resources> <item name="refresh" type="id"/> <item name="settings" type="id"/> </resources> 

in the Activity class call it

 ImageView refreshImg = new ImageView(activity); ImageView settingsImg = new ImageView(activity); refreshImg.setId(R.id.refresh); settingsImg .setId(R.id.settings); 
+15
Jan 20 2018-12-12T00:
source share

This will not work:

 layout.setId(100); 

But it will be:

 int id=100; layout.setId(id); 

In addition, this one too (credit: Aaron Dougherty):

 layout.setId(100+1); 
+13
Jan 20 2018-12-12T00:
source share

If you consistently put a group of components in a layout, as shown below:

 <LinearLayout> <ImageView> <TextView> <Button> <ImageView> <TextView> <Button> <ImageView> <TextView> <Button> ... </LinearLayout> 

then you can use for the loop and accordingly specify the identifiers:

 for(int i=0;i<totalGroups;i++) { ImageView img; TextView tv; Button b; ... // set other properties of above components img.setId(i); tv.setId(i); b.setId(i); ... //handle all events on these components here only ... //add all components to your main layout } 

Or, if you want to add only one group of components, you can use any integer that is large and does not conflict with other component identifiers in the resources. This will not be very controversial.

+3
Jan 20 '12 at 6:26
source share

For compatibility use: ViewCompat.generateViewId()

+2
Nov 16 '18 at 4:16
source share

You can define your identifiers as resources, and then use setId() for the view to set it. Define an identifier in the XML file, for example:

 <resources> <item type="id">your id name</item> </resources> 

then use in java file as ..

 layout.setId(R.id.<your id name>) 
+1
Jan 20 2018-12-12T00:
source share

Try this code! This should help give an idea.

activity_prac_main.xml

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:text="@string/edit_message" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/display_txt" android:textStyle="bold" android:textSize="18sp" android:textAlignment="center" android:layout_gravity="center_horizontal"/> <GridLayout android:id="@+id/my_grid" android:layout_width="match_parent" android:layout_height="wrap_content" android:rowCount="4"> <LinearLayout android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/linear_view"> <Button android:text="@string/button_send" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/my_btn" android:layout_gravity="center_horizontal"/> <TextView android:text="@string/edit_message" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/my_txt" android:textSize="18sp" /> </LinearLayout> </GridLayout> </LinearLayout> 

here is the rest of the code

  public class AnotherActivity extends AppCompatActivity { private int count = 1; List<Integer> gridArray; private TextView myDisplayText; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); gridArray = new ArrayList<>(); gridArray.add(Integer.valueOf(1)); setContentView(R.layout.activity_prac_main); findViews(); } private void findViews(){ GridLayout gridLayout = (GridLayout)findViewById(R.id.my_grid); gridLayout.setColumnCount(4); LinearLayout linearLayout = (LinearLayout) gridLayout.findViewById(R.id.linear_view); linearLayout.setTag("1"); Button myButton = (Button) linearLayout.findViewById(R.id.my_btn); myButton.setTag("1"); TextView myText = (TextView) linearLayout.findViewById(R.id.my_txt); myText.setText("1"); myDisplayText = (TextView) findViewById(R.id.display_txt); myButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { TextView txt = (TextView) view; myDisplayText.setText("PRESS " + txt.getTag().toString()); if(count < 24) { createView(); } else{ dialogBox(); } } }); } private void createView(){ LinearLayout ll = new LinearLayout(this); ll.setId(Integer.valueOf(R.id.new_view_id)); ll.setTag(String.valueOf(count+1)); Button newBtn = createButton(); newBtn.setId(Integer.valueOf(R.id.new_btn_id)); newBtn.setTag(String.valueOf(count+1)); TextView txtView = createText(); txtView.setId(Integer.valueOf(R.id.new_txt_id)); txtView.setTag(String.valueOf(count+1)); txtView.setText(String.valueOf(count+1)); GridLayout gridLayout = (GridLayout)findViewById(R.id.my_grid); ll.addView(newBtn); ll.addView(txtView); ll.setOrientation(LinearLayout.VERTICAL); gridLayout.addView(ll); count++; } private Button createButton(){ Button myBtn = new Button(this); myBtn.setText(R.string.button_send); myBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { TextView txt = (TextView) view; myDisplayText.setText("PRESS " + txt.getTag().toString()); if(count < 24) { createView(); } else{ dialogBox(); } } }); return myBtn; } public void dialogBox() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setMessage("GRID IS FULL!"); alertDialogBuilder.setPositiveButton("DELETE", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { GridLayout gridLayout = (GridLayout)findViewById(R.id.my_grid); gridLayout.removeAllViews(); count = 0; createView(); } }); alertDialogBuilder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } private TextView createText(){ TextView myTxt = new TextView(this); myTxt.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18); return myTxt; } } 

As you can see, the identifiers were created in the file res โ†’ values โ€‹โ€‹-> ids.

when creating views, the dynamic id is the same for the views.

Each TextView has the same identifier. Each button has the same identifier. each layout shares the same identifier.

Identifiers are important only for accessing the contents of views.

However, a tag is what makes each view unique to each.

Hope this helps you!

+1
Dec 19 '16 at 6:34
source share

I went about it differently.
Created his own R.id HashMap.
Than used the value for the view.setID () part.
String is an identifier, Integer is its value.

 Private HashMap<String, Integer> idMap= new HashMap<String, Integer>(); private int getRandomId(){ boolean notInGeneralResourses = false; boolean foundInIdMap = false; String packageName = mainActivity.getPackageName(); Random rnd = new Random(); String name =""; //Repaet loop in case random number already exists while(true) { // Step 1 - generate a random id int generated_id = rnd.nextInt(999999); // Step 2 - Check R.id try{ name = mainActivity.getResources().getResourceName(generated_id); }catch(Exception e){ name = null; } notInGeneralResourses = false; if (name == null || !name.startsWith(packageName)) { notInGeneralResourses = true; }else{ notInGeneralResourses = false; localLog("Found in R.id list."); } // Step 3 - Check in id HashMap if(notInGeneralResourses){ List<Integer> valueList = new ArrayList<Integer>(idMap.values()); foundInIdMap = false; for (Integer value : valueList) { if (generated_id == value) { foundInIdMap = true; localLog("Found in idMAp."); } } } // Step 4 - Return ID, or loop again. if (!foundInIdMap) { localLog("ID clear for use. "+generated_id); return generated_id; } } } 

and install:

  String idName = "someName"; int generated_R_id = getRandomId(); idMap.put(idName,generated_R_id); someView.setId(idMap.get(idName)); 

Now at any time you can simply:

 ImageView test = (ImageView) mainActivity.findViewById(idMap.get("somName")); 

and check it out -

  test.setImageResource(R.drawable.differentPic); 

PS I wrote it like this for ease of explanation.
Obviously, this can be written better and more compactly.

0
Nov 15 '18 at 14:32
source share

All you have to do is call ViewCompat.generateViewId()

For example:

 val textView = TextView(this) textView.text = "Hello World" textView.setLayoutParams(ViewGroup.LayoutParams(MATCH_PARENT, WRAP_CONTENT)) textView.id = ViewCompat.generateViewId() 
0
Feb 03 '19 at 18:56
source share



All Articles