Android ImageButton OnClick给出空指针异常

时间:2015-09-09 18:07:50

标签: android

我从一个菜单选项中调用poup对话框,该菜单选项用以下内容登录:然后将Twitter和Google徽标显示为2个图像按钮。

AlertDialog.Builder alertadd = new AlertDialog.Builder(
            SummaryActivity.this);
    LayoutInflater factory = LayoutInflater.from(SummaryActivity.this);
    final View view = factory.inflate(R.layout.social_network_selection, null);
    alertadd.setView(view);

它会膨胀包含2个图像按钮的视图。

当我添加代码

    googleButton2 = (ImageButton)findViewById(R.id.googleButton);
    twitterButton2 = (ImageButton)findViewById(R.id.twitterButton);

一切正常,但是当我添加

googleButton2.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

           Toast.makeText(MyAndroidAppActivity.this,
            "googleButton2 is clicked!", Toast.LENGTH_SHORT).show();

        }

    });

它与空指针崩溃。不是当我点击按钮但第二个我调用包含ImageButtons

的AlertDialog时

如何将监听器添加到AlertDialog膨胀视图上的图像按钮?

logcat的

java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
        at android.support.v7.internal.view.SupportMenuInflater$InflatedOnMenuItemClickListener.onMenuItemClick(SupportMenuInflater.java:259)
        at android.support.v7.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:149)
        at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:958)
        at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:948)
        at android.support.v7.internal.view.menu.MenuPopupHelper.onItemClick(MenuPopupHelper.java:191)

2 个答案:

答案 0 :(得分:1)

问题出在这些方面,

{1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 1000: 1, 100: 2}

findViewById(int)方法无法在上下文布局中找到id因此返回 null

解决方案

您必须使用findViewById方法来查找布局上下文膨胀的视图。

以下是您的任务所需的解决方案,

googleButton2 = (ImageButton)findViewById(R.id.googleButton);
twitterButton2 = (ImageButton)findViewById(R.id.twitterButton);

答案 1 :(得分:0)

使用View视图的名称调用imagebutton,使用getClick使用getBaseContext()

 AlertDialog.Builder alertadd = new AlertDialog.Builder(
                SummaryActivity.this);
        LayoutInflater factory = LayoutInflater.from(SummaryActivity.this);
        final View view = factory.inflate(R.layout.social_network_selection, null);
    ImageButton googleButton2 = (ImageButton)view.findViewById(R.id.googleButton);
        ImageButton twitterButton2 = (ImageButton)view.findViewById(R.id.twitterButton);

    googleButton2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

               Toast.makeText(getBaseContext(),
                "googleButton2 is clicked!", Toast.LENGTH_SHORT).show();

            }

        });
        alertadd.setView(view);