检查何时仅检查onClick?

时间:2013-12-06 00:18:54

标签: android

我有一个复选框,选中后会生成一个位图,然后将该位图保存到内部存储。然后,在gridView适配器中,我使用FileInputstream检查内部存储中的位图。

问题是复选框的onClick方法也在扩展baseadapter的类中。

按照现在的方式,当我启动我的应用程序时,它会自动检查位图,然后返回一个FileNotFound异常,然后复选框的onClick没有做任何事情。

我想到了这一点,并意识到它检查它的原因是它在我第一次打开我的应用程序时创建了gridView(应该是这样)。换句话说,它检查文件,因为它在我的gridView适配器的getView()方法中:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // Try to reuse the views
    ImageView view = (ImageView) convertView;
    // if convert view is null then create a new instance else reuse it
    if (view == null) {
        view = new ImageView(Context);
        Log.d("GridViewAdapter", "new imageView added");
    }
    try {
        Bitmap bitmapA = null;
        FileInputStream in = Context.openFileInput("bitmapA");
        bitmapA = BitmapFactory.decodeStream(in);
        in.close();
        /*BufferedInputStream buf = new BufferedInputStream(in);
        byte[] bitMapA = new byte[buf.available()];
        buf.read(bitMapA);
        Bitmap bM = BitmapFactory.decodeByteArray(bitMapA, 0, bitMapA.length);
        */view.setImageBitmap(bitmapA);
        if (in != null) {
            in.close();
        }
        /*if (buf != null) {
            buf.close();
        }*/
    } catch (Exception e) {
        e.printStackTrace();
    }
    view.setImageResource(drawables.get(position));
    view.setScaleType(ImageView.ScaleType.CENTER_CROP);
    view.setLayoutParams(new android.widget.GridView.LayoutParams(70, 70));
    view.setTag(String.valueOf(position));
    return view;
}

如果选中复选框,是否有办法让它检查内部存储? 请注意,复选框的onClick方法在一个类中,而我在另一个类中获取位图。

以下是我的两个完整课程:

AppInfoAdapter(带有onClick方法的那个---我只会在这里发布所需的编码):

package com.example.awesomefilebuilderwidget;

IMPORTS

public class AppInfoAdapter extends BaseAdapter {
private Context mContext;
private List<ResolveInfo> mListAppInfo;
private PackageManager mPackManager;
private List<ResolveInfo> originalListAppInfo;
private Filter filter;
private String fname;

public AppInfoAdapter(Context c, List<ResolveInfo> listApp,
        PackageManager pm) {
    mContext = c;
    this.originalListAppInfo = this.mListAppInfo = listApp;
    mPackManager = pm;
    Log.d("AppInfoAdapter", "top");
}

@Override
public int getCount() {
    Log.d("AppInfoAdapter", "getCount()");
    return mListAppInfo.size();
}

@Override
public Object getItem(int position) {
    Log.d("AppInfoAdapter", "getItem");
    return mListAppInfo.get(position);
}

@Override
public long getItemId(int position) {
    Log.d("AppInfoAdapter", "getItemId");
    return position;
}

public static Bitmap scaleDownBitmap(Bitmap default_b, int newHeight, Context c) {

    final float densityMultiplier = c.getResources().getDisplayMetrics().density;

    int h= (int) (100*densityMultiplier);
    int w= (int) (h * default_b.getWidth()/((double) default_b.getHeight()));

    default_b=Bitmap.createScaledBitmap(default_b, w, h, true);
    // TO SOLVE LOOK AT HERE:http://stackoverflow.com/questions/15517176/passing-bitmap-to-other-activity-getting-message-on-logcat-failed-binder-transac
    return default_b;
}

public void SaveImage(Bitmap default_b) {

    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/saved_images");
    myDir.mkdirs();
    Random generator = new Random();
    int n = 100000;
    n = generator.nextInt(n);
    String fname = "Image-" + n +".png";
    File file = new File (myDir, fname);
    Log.i("AppInfoAdapter", "" + file);
    if (file.exists()) file.delete();
    try {
        // File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
            //  + "/" + fname + ".png");
        FileOutputStream out = mContext.getApplicationContext().openFileOutput("bitmapA", Context.MODE_WORLD_WRITEABLE);
        // FileOutputStream out = new FileOutputStream(file);
        default_b.compress(Bitmap.CompressFormat.PNG, 90, out);
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    // get the selected entry
    final ResolveInfo entry = (ResolveInfo) mListAppInfo.get(position);

    // reference to convertView
    View v = convertView;

    // inflate new layout if null
    if (v == null) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        v = inflater.inflate(R.layout.layout_appinfo, null);
        Log.d("AppInfoAdapter", "New layout inflated");
    }

    // load controls from layout resources
    ImageView ivAppIcon = (ImageView) v.findViewById(R.id.ivIcon);
    TextView tvAppName = (TextView) v.findViewById(R.id.tvName);
    TextView tvPkgName = (TextView) v.findViewById(R.id.tvPack);
    final CheckBox addCheckbox = (CheckBox) v
            .findViewById(R.id.addCheckbox);
    Log.d("AppInfoAdapter", "Controls from layout Resources Loaded");

    // set data to display
    ivAppIcon.setImageDrawable(entry.loadIcon(mPackManager));
    tvAppName.setText(entry.activityInfo.loadLabel(mPackManager));
    tvPkgName.setText(entry.activityInfo.packageName);

    Log.d("AppInfoAdapter", "Data Set 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.activityInfo.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
                                scaleDownBitmap(default_b, 100, v.getContext());
                                Log.d("AppInfoAdapter", "Scale Bitmap Chosen");

                                SaveImage(default_b);
                                Log.d("AppInfoAdapter", "Scaled BM saved to External Storage");

                                Intent intent = new Intent(v.getContext(), GridViewAdapter.class);
                                // intent.hasExtra("bitmapA");
                                v.getContext().startActivity(intent);
                                Log.d("AppInfoAdapter", "Intent started to send Bitmap");

                            }
                        }
                    } else {
                        System.out.println("Un-Checked");
                    }

                }
            });

    // return view
    return v;
}

GridViewAdapter:

package com.example.awesomefilebuilderwidget;

IMPORTS

public class GridViewAdapter extends BaseAdapter {
private Context Context;

// Keep all Images in array list
public ArrayList<Integer> drawables = new ArrayList<Integer>();

// Constructor
public GridViewAdapter(Context c){
    Context = c;
    Log.d("GridViewAdapter", "Constructor is set");

    drawables.add(R.drawable.pattern1);
    Log.d("GridViewAdapter", "pattern1 added");

    drawables.add(R.drawable.pattern2);
    Log.d("GridViewAdapter", "pattern2 added");

    drawables.add(R.drawable.trashcan);
    Log.d("GridViewAdapter", "trashcan added");

    drawables.add(R.drawable.ic_launcher);
    Log.d("GridViewAdapter", "ic_launcher added");

    Bitmap default_b = BitmapFactory.decodeFile("picture");  
}

@Override
// How many items are in the data set represented by this Adapter
public int getCount() {
    return drawables.size();
}

@Override
// Get the data item associated with the specified position in the
// data set
public Object getItem(int position) {
    return drawables.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // Try to reuse the views
    ImageView view = (ImageView) convertView;
    // if convert view is null then create a new instance else reuse it
    if (view == null) {
        view = new ImageView(Context);
        Log.d("GridViewAdapter", "new imageView added");
    }
    try {
        Bitmap bitmapA = null;
        FileInputStream in = Context.openFileInput("bitmapA");
        bitmapA = BitmapFactory.decodeStream(in);
        in.close();
        /*BufferedInputStream buf = new BufferedInputStream(in);
        byte[] bitMapA = new byte[buf.available()];
        buf.read(bitMapA);
        Bitmap bM = BitmapFactory.decodeByteArray(bitMapA, 0, bitMapA.length);
        */view.setImageBitmap(bitmapA);
        if (in != null) {
            in.close();
        }
        /*if (buf != null) {
            buf.close();
        }*/
    } catch (Exception e) {
        e.printStackTrace();
    }
    view.setImageResource(drawables.get(position));
    view.setScaleType(ImageView.ScaleType.CENTER_CROP);
    view.setLayoutParams(new android.widget.GridView.LayoutParams(70, 70));
    view.setTag(String.valueOf(position));
    return view;
}

}

进一步更新的编码:

 @Override
public View getView(int position, View convertView, ViewGroup parent) {
    // Try to reuse the views
    ImageView view = (ImageView) convertView;
    boolean checked = (mCheckBox==null)?false:(((CheckBox)  mCheckBox).isChecked());
    // if convert view is null then create a new instance else reuse it
    if (view == null) {
        view = new ImageView(Context);
        Log.d("GridViewAdapter", "new imageView added");
    }
    if(checked = true){
    try {
        Bitmap bitmapA = null;
        FileInputStream in = Context.openFileInput("bitmapA");
        bitmapA = BitmapFactory.decodeStream(in);
        in.close();
        /*BufferedInputStream buf = new BufferedInputStream(in);
        byte[] bitMapA = new byte[buf.available()];
        buf.read(bitMapA);
        Bitmap bM = BitmapFactory.decodeByteArray(bitMapA, 0, bitMapA.length);
        */view.setImageBitmap(bitmapA);
        if (in != null) {
            in.close();
        }
        /*if (buf != null) {
            buf.close();
        }*/
    } catch (Exception e) {
        e.printStackTrace();
    }}

我加上这个方法:

public void setCheckBox(CheckBox checkbox){
    mCheckBox=checkbox;
}

和这个变量:

CheckBox mCheckBox=null;

1 个答案:

答案 0 :(得分:0)

您无需在适配器中侦听onClick事件。 相反,您可以阅读复选框状态。

为此,在适配器中添加字段和setter:

CheckBox mCheckBox=null;

public void setCheckBox( CheckBox  checkbox){

         mCheckBox=checkbox;
}

然后,在getView()中,在开头添加thiss行;

boolean checked = (mCheckBox==null)?false:(((CheckBox)  mCheckBox).isChecked());

<强>更新

然后在你的活动中,我想你有类似

的东西
GridViewAdapter mGridViewAdapter= new GridViewAdapter(this);

所以,下面你要添加:

CheckBox mCheckBox = findViewById(R,id.YOURCHECKBOXID);
mGridViewAdapter.setCheckBox(mCheckBox); 

就是这样!