2013-07-23 102 views
0

当我使用setId(D),我收到此错误信息:为什么我收到SETID()未定义

The method setId() is undefined for the type MainActivity 

如果我不能在这种情况下使用setId(),有没有其他的方法来设置一个ID为TextView动态?

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" /> 

... 
+3

因为'Activity'没有'setId()'方法。你需要在'View'或类似的地方使用它。但是,看看你的代码,我对你在做什么感到困惑。一个id不应该被用作计数器。 – Geobits

+0

谢谢你的答案。它不会是一个缩短的计数器。每个TextView将根据其他算法由文本和数字填充。 – user2556278

回答

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"); 
    } 
} 
... 
+0

它看起来可以工作。 “未定义的getId()”消失了,但我得到另一个错误:“D无法解析或不是字段”。谢谢 – user2556278

+0

即时通讯不知道哪里有'D'来自你的代码,但是最好使用'textview_D'而不是另一个'D'(见编辑) – petey

+0

D应该是TextView ID的引用,如下所示:if D = 1使用android:id =“@ + id/2”执行TextView如果D = 2执行TextView与android:id =“@ + id/2” – user2556278

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)

请注意,还有其他方式来存储计数器。通常在你的活动中一个简单的领域就足够了。

+0

谢谢。当我写信给詹姆斯时,我想获取文本和数字,这些文本和数字将根据另一个函数动态更改。结果(文本/数字)应该在屏幕上逐一显示,例如十行。 – user2556278

相关问题