2013-02-17 44 views
0

我有一個包含一個按鈕,它被稱爲按鈕/ XML不能包含佈局內訪問元素:Android的

<Button 
    android:id="@+id/loginButton1" 
    style="?android:attr/buttonStyleSmall" 
    android:layout_width="match_parent" 
    android:layout_height="40dp" 
    android:background="@drawable/button_background" 
    android:text="Button" /> 

我有另一個佈局稱爲的XML文件login.xml,其中包含兩次button.xml。

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    android:paddingLeft="30dp" 
    android:paddingRight="30dp" 
    android:paddingTop="30dp"> 

    <include 
     android:id="@+id/loginUser1" 
     android:layout_width="match_parent" 
     android:layout_height="30dp" 
     layout="@layout/button" /> 

     <include 
      android:id="@+id/loginUser2" 
      android:layout_width="match_parent" 
      android:layout_height="30dp" 
      android:layout_marginTop="20dp" 
      layout="@layout/button" /> 

</LinearLayout> 

現在,當我試圖訪問每個按鈕seperately在我的Java類中,我得到一個錯誤,一邊指着loginUser1。錯誤說NullPointerException。由於我確實知道loginUser1存在,爲什麼我仍然收到錯誤?

final LinearLayout layout = (LinearLayout)findViewById(R.id.loginUser1); //null pointer exception HERE! 
    final Button button = (Button)layout.findViewById(R.id.loginButton1); 
    button.setText("button one"); 

回答

2

查看您的日誌貓。您應該獲得ClassCastException而不是NullPointerException。問題是編號爲R.id.loginUser1的視圖實際上是Button而不是LinearLayout。下面的代碼應該很好地工作:

final Button first = (Button) findViewById(R.id.loginUser1); 
final Button second = (Button) findViewById(R.id.loginUser2); 

first.setText("button one"); 
second.setText("button two"); 

而且,請注意,ID爲R.id.loginButton1了沒有按鈕,因爲它的ID被include標籤覆蓋

0

你應該先做到這一點

最終按鈕=(Button)findViewById(R.id.loginButton1); first.setText(「your text」);

因爲loginUser1是一個按鈕而不是LinearLayout。

+0

我很抱歉,但這只是改變了第一個按鈕的文本......你如何建議我改變第二個文本的文本? – BurninatorDor 2013-02-17 05:39:15