0

我有一个按钮,当我单击它时,会显示一个弹出窗口,其中包含 4 个按钮。根据用户在弹出窗口中单击的按钮,弹出触发按钮将自行更新。但是我在下面的代码中遇到了一个无法 getId() 的问题。

public void pressCell(View view) {

    final ImageButton popup = (ImageButton) findViewById(view.getId());

    LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
            .getSystemService(LAYOUT_INFLATER_SERVICE);
    View popupView = layoutInflater.inflate(R.layout.popup, null);
    final PopupWindow popupWindow = new PopupWindow(popupView,
            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    popupWindow.setFocusable(true);

    popupView.findViewById(popupView.getId()).setOnClickListener(
            new OnClickListener() {
                @Override
                public void onClick(View view) {
                    switch (view.getId()) {
                    case R.id.button1:
                        popup.setImageResource(R.drawable.num1);
                    case R.id.button2:
                        popup.setImageResource(R.drawable.num2);
                    case R.id.button3:
                        popup.setImageResource(R.drawable.num3);
                    case R.id.button4:
                        popup.setImageResource(R.drawable.num4);

                    }
                    popupWindow.dismiss();
                }

            });

    popupWindow.showAsDropDown(findViewById(view.getId()), -120, -2
            * findViewById(view.getId()).getHeight());

}

pressCell 是触发按钮的 onCLick 函数:

<ImageButton
            android:id="@+id/cell1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="pressCell"
            android:src="@drawable/num3" />

谁能告诉我这里有什么问题?谢谢。

4

2 回答 2

0

应该使用获取 ImageButton 的参考;

ImageButton imageButton = (ImageButton)popupView.findViewById(R.id.cell1);

在您的代码 setOnClickLİsener 方法中,您将获得 popupView 参考;

popupView.findViewById(popupView.getId()).setOnClickListener(
        new OnClickListener() {
            @Override
            public void onClick(View view) {  // clicked view popupView.
                switch (view.getId()) {
                case R.id.button1:
                    popup.setImageResource(R.drawable.num1);
                case R.id.button2:
                    popup.setImageResource(R.drawable.num2);
                case R.id.button3:
                    popup.setImageResource(R.drawable.num3);
                case R.id.button4:
                    popup.setImageResource(R.drawable.num4);

                }
                popupWindow.dismiss();
            }

        }); 
于 2013-10-08T05:22:29.337 回答
0

在设置 onClickListener 之前,您正在执行以下操作:

 popupView.findViewById(popupView.getId()).setOnClickListener

您不应该view.getId改为传递给 findViewById 方法吗?

于 2013-10-08T05:24:00.803 回答