将应用程序图标从listView获取到gridView

时间:2013-11-28 00:49:36

标签: java android android-listview android-gridview android-icons

我有一个用户安装的应用程序的listView。以下是每个listView项的布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="?android:attr/listPreferredItemHeight"
 android:padding="5dip" 
 >

 <ImageView
  android:id="@+id/ivIcon"
  android:layout_width="wrap_content"
  android:layout_height="fill_parent"
  android:layout_marginRight="5dip"
  android:scaleType="center"
  android:contentDescription="@string/desc"
 />

 <LinearLayout
  android:orientation="vertical"
  android:layout_width="0dip"
  android:layout_height="fill_parent"
  android:layout_weight="1"    
 >

  <TextView
      android:id="@+id/tvName"
      android:layout_width="fill_parent"
      android:layout_height="0dip"
      android:layout_weight="1"
      android:gravity="center_vertical"         
  />

  <TextView
      android:id="@+id/tvPack"
      android:layout_width="fill_parent"
      android:layout_height="0dip"
      android:layout_weight="1"
      android:singleLine="true"
      android:ellipsize="marquee"         
  />

</LinearLayout>

<CheckBox
  android:id="@+id/addCheckbox"
  android:layout_width="0dp"
  android:layout_height="fill_parent"
  android:layout_weight="0.3"
  android:gravity="center_vertical"
  android:focusable="false" 
/>

</LinearLayout>

然后我在这里有listView的适配器:

package com.example.awesomefilebuilderwidget;

IMPORTS

public class AppInfoAdapter extends BaseAdapter implements Filterable {
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);
    if (file.exists()) file.delete();
    try {
        File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/" + fname + ".png");
        FileOutputStream out = new FileOutputStream(f);
        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.putExtra("picture", fname);
                                v.getContext().startActivity(intent);
                                Log.d("AppInfoAdapter", "Intent started to send Bitmap");

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

                }
            });

    // return view
    return v;
}

我正在获取用户安装的应用程序列表,如下所示:

package com.example.awesomefilebuilderwidget;
IMPORTS

public class Utilities {

/*
 * Get all installed application on mobile and return a list
 * @param   c   Context of application
 * @return  list of installed applications
 */
public static List<ResolveInfo> getInstalledApplications(Context c) {
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);
    return c.getPackageManager().queryIntentActivities(intent, PackageManager.GET_ACTIVITIES);
}
 }

现在 我想要做的是,当点击listView项的复选框时,listView项的应用程序的图标然后变成位图(或可绘制),以便它可以发送到我的gridView适配器这里:

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 {
        FileInputStream in = new FileInputStream("picture");
        BufferedInputStream buf = new BufferedInputStream(in);
        byte[] bitMapA = new byte[buf.available()];
        buf.read(bitMapA);
        Bitmap bM = BitmapFactory.decodeByteArray(bitMapA, 0, bitMapA.length);
        view.setImageBitmap(bM);
        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;
}

}

这样,当单击复选框时,图标会出现在我的gridView中。 “

我尝试发送带有意图的byteArrays(但是被告知这会很糟糕,因为它会减慢速度),我也尝试过FileOutput和FileInput流,我也试过使用onActivityResult和一些其他的事情。

为了帮助澄清我的意思,这就是我现在所拥有的:

enter image description here

例如,当我点击新闻的复选框时,新闻图标应出现在滑动抽屉后面的gridView中。

我可以做什么?请至少给我一些提示或帮助我。我已经尝试了所有我能想到的并且没有得到它的工作。 我知道这很难读,但如果有人能帮我解决这个问题,我会非常感激。

添加更改后的编码:

saveImage类:

    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);
    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);
        default_b.compress(Bitmap.CompressFormat.PNG, 90, out);
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

有意图:

Intent intent = new Intent(v.getContext(), GridViewAdapter.class);
                                intent.hasExtra("bitmapA");
                                v.getContext().startActivity(intent);

接收课程:

try {
        FileInputStream in = Context.openFileInput("bitmapA");
        BufferedInputStream buf = new BufferedInputStream(in);
        byte[] bitMapA = new byte[buf.available()];
        buf.read(bitMapA);
        Bitmap bM = BitmapFactory.decodeByteArray(bitMapA, 0, bitMapA.length);
        view.setImageBitmap(bM);
        if (in != null) {
            in.close();
        }
        if (buf != null) {
            buf.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

0 个答案:

没有答案