0

当我使用setId(D)时,我收到以下错误消息:

The method setId() is undefined for the type MainActivity

如果我不能setId()在这种情况下使用,还有其他方法可以TextView动态设置 ID 吗?

主要活动:

...
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...

活动主.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" />

...
4

2 回答 2

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)

请注意,还有其他方法可以存储计数器。通常,活动中的一个简单字段就足够了。

于 2013-07-23T16:09:46.503 回答
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");
     }
} 
...
于 2013-07-23T16:08:08.423 回答