简体   繁体   中英

Android - Different Ids for the same include Layout

I have a layout which I have to Include several times. It consists of a TextView and an ImageView :

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="40dp"
    android:background="@drawable/back2"
    android:id="@+id/id_1"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/id_2"
    android:textSize="15dp"
    android:typeface="sans"
    android:textColor="#ffffff" />

Now I want to set the text programmatically, but the problem that I'm facing is, that the TextView now always has the same Id, because I'm including the same Layout several times. Is there a way to programmatically include a Layout and always change the Id for each included layout?

What I'd do is, when you need to access the views on a particular instance of the included layout:

ViewGroup instance = (ViewGroup) findViewById(R.id.included1); // Replace ViewGroup with whatever your particlar type is
ImageView iView = (ImageView) instance.findViewById(R.id.id_1);
TextView tView = (TextView) instance.findViewById(R.id.id_2);

您可以动态创建TextView,然后使用TextView.setId(int id)设置该View的id,以便稍后可以使用新id调用它。

For each textview

Change the id in the line android:id="@+id/id_2" to a different id.

For example:

android:id="@+id/id_4"

To add them programmatically you can do this:

            TextView Label3 = new TextView(this);
            Label3.setId(300);
            Label3.setTextAppearance(this, android.R.attr.textAppearanceMedium);
            Label3.setLayoutParams(labelParams);
            Label3.setText("My textViewCaption:");
            ll3.addView(Label3);

and if you set Label3 as a global variable, you can access it to change it, via setText

Programmatically you can loop through this and set the Ids while you loop

您可以使用它来更改TextView ID
TextView textview = new TextView(this); textview.setId(int id);

As far as I know there is no way to do this. You'll have to create the layout w/o using <include> if you want the ids in your XML layout to be unique.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM