2015-02-17 62 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

相关问题