2015-02-17 63 views
0

這是我第一次創建Android應用程序,但我不確定如何解決此問題。我試圖通過ID將ImageButton變量指向現有的ImageButton,但我仍然收到NullPointerException。下面的代碼:ImageButton在賦值後爲'null'

... 
    import android.widget.ImageButton; 

    public class StartActivity extends ActionBarActivity { 
     ImageButton addButton; 

     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_start); 
       addButton = (ImageButton) findViewById(R.id.add_category_button); 
     }... 

ImageButton位於佈局card_categories。下面是該佈局的XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:background="@color/main_page" 
android:weightSum="1"> 


    <ImageButton 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/add_category_button" 
     android:layout_gravity="right" 
     android:background="@drawable/add_button" 
     android:width="50dp" 
     android:height="50dp" 
    /> 
</LinearLayout> 

我不知道這個問題是不正確的id,或者是什麼,但它不是正確抽取在XML中ImageButton。謝謝你的幫助!

更新:我試圖在setContentView(R.layout.card_categories)之後分配ImageButton,但它仍然爲空。

OnClickListener myCardsHandler = new OnClickListener() { 
    public void onClick(View v) { 
     setContentView(R.layout.card_categories); 
     addButton = (ImageButton) findViewById(R.id.add_category_button); 
     loadCategories(dbHandler, categories); 
    } 
}; 
+2

_「的ImageButton的位於佈局card_categories」 _但你誇大'R.layout.activity_start'因此,如何將你希望得到你的'ImageButton'? – 2015-02-17 23:15:45

+0

確保:'activity_start.xml'包含'ImageButton'。我認爲你可以'setContentView'爲不同的佈局。 – 2015-02-17 23:18:07

+0

你在OnClickListener好友中指定它:)這應該在Activity#OnCreate生命週期方法中理想地發生! – 2015-02-17 23:41:03

回答

0

試試這個

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.card_categories); 
     addButton = (ImageButton) findViewById(R.id.add_category_button); 
     addButton.setOnClickListener(myCardsHandler); 
    } 

    OnClickListener myCardsHandler = new OnClickListener() { 
     public void onClick(View v) { 

      loadCategories(dbHandler, categories); 
     } 
    }; 
0

您在setContentView方法中設置了錯誤的佈局。所以這並不奇怪,編譯器在那裏找不到那個名字的任何ImageButton

要麼誇大card_categories:

setContentView(R.layout.activity_start); 

或將您的ImageButton在佈局當前已設置。

+0

我調用它後,我調用新的setContentView(R.layout.card_categories),但它仍然給我一個Null值爲addButton – Rhuarc13 2015-02-17 23:28:08

相關問題