当我使用setId(D)
时,收到以下错误消息:
The method setId() is undefined for the type MainActivity
如果在这种情况下我无法使用setId()
,是否有其他方法可以动态设置TextView
的ID?
MainActivity:
...
public void onClick(View view) {
...
if (D>=0) {screen();}
D=D+1;
}
public void screen() {
setId(D);
if (D==0) {
TextView D = (TextView) findViewById(R.id.D);
D.setText("the button was pressed: " +D+ "time");
}
}
...
// I dont want to write twenty conditions
if (D==1) {
TextView D1 = (TextView) findViewById(R.id.1);
D1.setText("some text" +num);
}
if (D==2) {
TextView D2 = (TextView) findViewById(R.id.2);
D2.setText("some text" +num) ;
}
if (D==3) {
TextView D3 = (TextView) findViewById(R.id.3);
D3.setText("some text" +num) ;
}
// and so on...
activity_main.xml中:
<TextView
android:id="@+id/1"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_marginTop="20dp" />
<TextView
android:id="@+id/2"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_marginTop="40dp" />
<TextView
android:id="@+id/3"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_marginTop="60dp" />
...
答案 0 :(得分:2)
ID无意更改或用作变量。对于附加到视图的元数据,您可能需要查看view.tag http://developer.android.com/reference/android/view/View.html#getTag()
您还可以按标签检索视图。 http://developer.android.com/reference/android/view/View.html#findViewWithTag(java.lang.Object)
请注意,还有其他方法可以存储计数器。通常,活动中的一个简单字段就足够了。
答案 1 :(得分:0)
...
public void onClick(View view) {
...
// pass the clicked view
if (D>=0) {screen(view);}
D=D+1;
}
public void screen(View view) {
/// call setId on the view that was clicked
view.setId(D);
if (D==0) { // maybe you want !=0 here instead
// D already should exist as a number, notice the name change in next 2 line
TextView textview_D = (TextView) findViewById(R.id.D);
textview_D.setText("the button was pressed: " +D+ "time");
}
}
...