Android:在自定义适配器中加载应用图标

时间:2014-02-13 12:22:10

标签: android android-listview android-asynctask android-adapter baseadapter

我正在开发一个新的Home Launcher,目前使用listview来显示已安装的应用程序。我正在使用自定义适配器来提供应用程序名称和图标。如果我离开应用程序名称我没有问题,但是,如果我添加图标列表视图变得非常缓慢和无法使用。我也试过asynctask没有运气。这是我的适配器的相关部分:

public AppInfoAdapter(Context c, List list, ArrayList<String> appList, PackageManager pm, Resources resources) {
    mContext = c;
    mListAppInfo = list;
    mPackManager = pm;
    mAppList = appList;
    mResources = resources;
    activity = (Activity) c;
}

=====

   @Override

public View getView(int position, View convertView, ViewGroup parent) {

    View v = convertView;

    if(v == null) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        v = inflater.inflate(R.layout.launcher_adapter_row, null);
    }

    if (v != null) {
        mIcon = (ImageView) v.findViewById(R.id.imageView1);
        tvAppName = (TextView) v.findViewById(R.id.textView1);
    }

    new addItems().execute(tvAppName, mIcon, position);

    return v;
}

====

public class addItems extends AsyncTask<Object, String, Void> {

    private TextView title;
    private ImageView icon;
    private int pos;

    @Override
    protected Void doInBackground(final Object... parameters) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                title = (TextView) parameters[0];
                icon = (ImageView) parameters[1];
                pos = (Integer) parameters[2];

                entry = (ApplicationInfo) mListAppInfo.get(pos);

                icon.setImageDrawable(entry.loadIcon(mPackManager));
                title.setText(entry.loadLabel(mPackManager));
            }
        });

        return null;
    }
}

尝试使用listview和gridview。结果是一样的。由于口吃而滚动是不可能的。有什么建议?感谢

2 个答案:

答案 0 :(得分:4)

您再次在AsynchTask的Ui主题中加载数据,因此请更改您的AsynchTask ..

public class addItems extends AsyncTask<Object, String, Drawable> {

    private TextView title;
    private ImageView icon;
    private int pos;

    @Override
    protected Drawable doInBackground(final Object... parameters) {
        title = (TextView) parameters[0];
        icon = (ImageView) parameters[1];
        pos = (Integer) parameters[2];

        entry = (ApplicationInfo) mListAppInfo.get(pos);

        Drawable drawable = entry.loadIcon(mPackManager);
        return drawable;
    }

    @Override
    protected void onPostExecute(Drawable result) {
        super.onPostExecute(result);
        icon.setImageDrawable(result);
        title.setText(entry.loadLabel(mPackManager));
    }
}

这里我在另一个线程中加载drawable并将其传递给onPostexecute因此,在doInbackGround方法中,UI线程设置文本不是一项艰巨的任务。

答案 1 :(得分:1)

问题在于这句话

icon.setImageDrawable(entry.loadIcon(mPackManager));

这是因为在UI线程中调用了此方法loadIcon()。在UI线程上,如果您尝试解码位图,则会在滚动时导致打嗝。