简体   繁体   English

Android - 相同的不同ID包括布局

[英]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 : 它由TextViewImageView

<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. 现在我想以编程方式设置文本,但我面临的问题是, TextView现在总是具有相同的Id,因为我多次包含相同的Layout。 Is there a way to programmatically include a Layout and always change the Id for each included layout? 有没有办法以编程方式包含布局并始终更改每个包含的布局的ID?

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 对于每个textview

Change the id in the line android:id="@+id/id_2" to a different id. android:id="@+id/id_2"行中的id更改为其他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 如果将Label3设置为全局变量,则可以通过setText访问它以进行更改

Programmatically you can loop through this and set the Ids while you loop 以编程方式,您可以遍历此循环并在循环时设置ID

您可以使用它来更改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. 如果希望XML布局中的ID是唯一的,则必须使用<include>创建布局。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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