Android-同一包含布局的不同ID
我有一个布局,我必须包括几次。它由Android-同一包含布局的不同ID,android,Android,我有一个布局,我必须包括几次。它由文本视图和图像视图组成: <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" an
文本视图
和图像视图
组成:
<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" />
现在我想以编程方式设置文本,但我面临的问题是,
TextView
现在总是具有相同的Id,因为我多次包含相同的布局。是否有一种方法可以通过编程方式包含布局并始终更改每个包含布局的Id?据我所知,没有方法可以做到这一点。如果希望XML布局中的id是唯一的,则必须使用
创建布局,而不使用该布局。您可以动态创建TextView,然后使用TextView.setId(int id)
设置该视图的id,以便以后可以使用新id调用它。我要做的是,当需要访问包含布局的特定实例上的视图时:
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);
对于每个文本视图
将行android:id=“@+id/id_2”
中的id更改为其他id
例如:
android:id=“@+id/id_4”
要以编程方式添加它们,可以执行以下操作:
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);
如果将Label3设置为全局变量,则可以通过setText
通过编程方式,您可以在循环时循环并设置id您可以使用此选项更改TextView id
TextView TextView=新的TextView(此);
setId(int-id)代码>为什么不动态添加TextView?这就是我通常使用包含的布局进行添加的方式。我有几个不同的通用按钮设置(两个垂直按钮、两个水平按钮等),我反复使用它们,并根据它们包含的布局参考它们,以设置不同的文本和操作。