【问题标题】:ImageButton is 'null' after assignment分配后 ImageButton 为“空”
【发布时间】:2015-02-17 23:12:00
【问题描述】:

这是我第一次创建 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);
    }
};

【问题讨论】:

  • “ImageButton 位于布局 card_categories 中” 但您正在膨胀 R.layout.activity_start 那么您希望如何获得您的 ImageButton
  • 确保:activity_start.xml 包含 ImageButton。我想你可以 setContentView 到不同的布局。
  • 您在 OnClickListener 好友中分配它 :) 理想情况下,这应该发生在 Activity#OnCreate 生命周期方法中!

标签: java android android-button


【解决方案1】:

试试这个

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

【讨论】:

    【解决方案2】:

    您在 setContentView 方法中设置了错误的布局。所以毫不奇怪,编译器在那里找不到该名称的任何ImageButton

    要么扩充 card_categories:

    setContentView(R.layout.activity_start);
    

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

    【讨论】:

    • 我在调用新的 setContentView(R.layout.card_categories) 后将其移至,但它仍然为 addButton 提供了 Null 值
    猜你喜欢
    • 1970-01-01
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多