首页 文章

Intent不适用于onClick方法

提问于
浏览
0

我试图在复选框的onClick方法中使用intent,但是我得到的错误是方法startActivity未定义,并且构造函数Intent(new View.OnClickListener等)也是未定义的 . 这是我的代码:

final CheckBox addCheckbox = (CheckBox) v
            .findViewById(R.id.addCheckbox);

    // set data to display

    addCheckbox
            .setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (addCheckbox.isChecked()) {
                        System.out.println("Checked");
                        PackageManager pm = mContext.getPackageManager();
                        Drawable icon = null;
                        try {
                            icon = pm
                                    .getApplicationIcon(entry.packageName);
                        } catch (NameNotFoundException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        Drawable default_icon = pm.getDefaultActivityIcon();
                        if (icon instanceof BitmapDrawable
                                && default_icon instanceof BitmapDrawable) {
                            BitmapDrawable icon_bd = (BitmapDrawable) icon;
                            Bitmap icon_b = icon_bd.getBitmap();
                            BitmapDrawable default_bd = (BitmapDrawable) pm
                                    .getDefaultActivityIcon();
                            Bitmap default_b = default_bd.getBitmap();
                            if (icon_b == default_b) {
                                // It's the default icon


                                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                                default_b.compress(Bitmap.CompressFormat.PNG, 100, stream);
                                byte[] byteArray = stream.toByteArray();

                                Intent intent = new Intent(this, GridView.class);
                                intent.putExtra("picture", byteArray);
                                this.startActivity(intent);
                            }
                        }
                    } else {
                        System.out.println("Un-Checked");
                    }

                }
            });

2 回答

  • 0

    由于你在 listener 内, this 指的是 listener ,这就是你得到错误的原因

    “方法startActivity未定义”

    只需删除 this

    startActivity(intent);
    

    这是另一个错误的原因

    构造函数Intent(new View.OnClickListener ect ..)“

    使用单击的 View s Context 将是 Activity Context

    Intent intent = new Intent(v.getContext(), GridView.class);
    

    所以该块看起来像

    Intent intent = new Intent(v.getContext(), GridView.class);
    intent.putExtra("picture", byteArray);
    startActivity(intent);
    
  • 1

    使用以下代码重新编写代码

    Intent intent = new Intent(YOURACTIVITY_NAME.this, GridView.class);
    
    intent.putExtra("picture", byteArray);
    
     startActivity(intent);
    

相关问题