分配后'null'图像按钮



这是我第一次创建Android应用程序,我不知道如何解决这个问题。我试图通过ID将ImageButton变量指向现有的ImageButton,但我一直得到一个NullPointerException。这是代码:

    ...
    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);
    }
};

试试这个

@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);
       }
   };

您在setContentView方法中设置了错误的布局。因此,编译器在那里找不到任何该名称的ImageButton也就不足为奇了。

充气卡片类别:

setContentView(R.layout.activity_start);

或者将ImageButton放置在当前设置的布局中。

最新更新