ListView不允许我将<list>设置为列表

时间:2018-12-04 07:24:07

标签: android listview

我有一个列表:

  Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
    mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
    List<ResolveInfo> pkgAppsList = getApplicationContext().getPackageManager().queryIntentActivities(mainIntent, 0);

我想在适配器中设置它。我已经尝试过了:

adapter = new ArrayAdapter<List>(this, R.layout.listview_row_customizations, pkgAppsList) {

但是我遇到错误无法解析构造函数数组适配器...

我该如何解决?

2 个答案:

答案 0 :(得分:1)

尝试

adapter = new ArrayAdapter<ResolveInfo>(this, R.layout.listview_row_customizations, pkgAppsList)

答案 1 :(得分:0)

新ArrayAdapter中的列表不正确,而是写入对象类类型(ResolveInfo)。

如果您需要自定义布局(我猜是因为您使用的不是字符串列表,而是带有一些参数的对象),请按照以下说明操作:

构建自己的自定义ArrayAdapter:

    public class MyAdapter extends ArrayAdapter<ResolveInfo> {

    public MyAdapter(Context context, List<ResolveInfo> list) {
        super(context, 0, list);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ResolveInfo resolveInfo = getItem(position);

        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.item, parent, false);
        }

        TextView tvName = (TextView) convertView.findViewById(R.id.tvName);
        TextView tvPriority = (TextView) convertView.findViewById(R.id.tvPriority);

        tvName.setText(resolveInfo.resolvePackageName);
        tvPriority.setText("" + resolveInfo.priority);

        return convertView;
    }
}

创建一个名为item.xml的布局:

<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <TextView
        android:id="@+id/tvName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:text="TextView" />

    <TextView
        android:id="@+id/tvPriority"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:text="TextView" />
</RelativeLayout>

在“活动”中,通过以下方式调用它:

        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        List<ResolveInfo> pkgAppsList = getApplicationContext().getPackageManager().queryIntentActivities(mainIntent, 0);
        MyAdapter myAdapter = new MyAdapter(this, pkgAppsList);