findResourceById()返回null

时间:2012-01-30 21:29:17

标签: android android-layout android-xml android-button

我已经阅读了有关此主题的一些问题和答案,但没有一个问题适用于我的问题。

我的问题在以下代码中:

 public class Activity2 extends Activity {

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.alt);

}


public void buttonPress(View v){
    TextView tv1 = (TextView) findViewById(R.id.text1);
    TextView tv2 = (TextView) findViewById(R.id.text2);
    Button b1 = (Button) findViewById(R.id.button1);
    if((tv1 != null) & (tv2 != null) & (b1 != null)){
        tv1.setText(R.string.changed);
        tv2.setText(R.string.changed);
        b1.setText(R.string.changed);
    }
    else
        Toast.makeText(getApplicationContext(), "VIEW ELEMENTS ARE NOT BEING ASSIGNED", Toast.LENGTH_SHORT).show();
}

alt.xml看起来像这样

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
    android:name="@+id/text1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/stuff" />

<TextView
    android:name="@+id/text2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/stuff2" />

<Button
    android:name="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/buttonText"
    android:onClick="buttonPress" />        

在R.id中生成ID,但它们没有分配给我的两个TextView元素和一个Button元素。 (我每次都看到吐司弹出窗口)

有没有人有任何想法?

2 个答案:

答案 0 :(得分:7)

而不是android:name="..."使用android:id="@+id/..."

答案 1 :(得分:1)

尝试替换

android:name="@+id/text1"

通过

android:id="@+id/text1"