Intent不适用于onClick方法

时间:2013-10-31 23:05:31

标签: android android-intent

我试图在复选框的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 :(得分:1)

用以下代码替换您的代码

Intent intent = new Intent(YOURACTIVITY_NAME.this, GridView.class);

intent.putExtra("picture", byteArray);

 startActivity(intent);

答案 1 :(得分:0)

由于您位于listener内,this引用了listener,这就是您收到错误的原因

  

“方法startActivity未定义”

只需删除this

即可
startActivity(intent);

这是其他错误的原因

  

构造函数   意图(新的View.OnClickListener等)“

使用点击的View 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);