2012-01-30 45 views
0

我已閱讀了有關此主題的幾個問題和答案,但沒有一個適用於我的問題。findResourceById()返回null

我的問題是在下面的代碼:

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,但他們不是活得t被分配給我的兩個TextView元素和我的一個Button元素。 (我每次看到吐司都會彈出)

有沒有人有任何想法?

+1

你的意思寫的''&&代替'&'? – EboMike 2012-01-30 21:33:37

+0

@EboMike是的,謝謝,修復它和同樣的問題,雖然 – SmashCode 2012-01-30 21:35:57

回答

7

代替android:name="..."使用android:id="@+id/..."

+0

試過這個無濟於事。 ID正在生成,所以我不認爲它們是問題。 – SmashCode 2012-01-30 21:39:35

+0

我接受了這一點,我正在嘗試與其他人提出的更改並將其刪除。恢復後,這固定它。 – SmashCode 2012-01-30 21:43:46

+0

編輯:真棒。很高興它對你有效。 – bschultz 2012-01-30 21:45:37

1

嘗試更換

android:name="@+id/text1" 

通過

android:id="@+id/text1"