首页 > 解决方案 > 从 RecyclerView 作为字符串接收的数组中的 ListView

问题描述

我有一个主要活动Recyclerview,它显示一个列表图像和一个文本作为标题。

在主要活动中,我有三个数组列表;一个用于图像,一个用于标题,最后一个“array”用于字符串数组。

我将R.array.id作为字符串传递给下一个活动 On Click 中的项目MainActivity。我发送图像、标题和array.

在第二个Activity中,我检查传入意图,将它们分配给字符串。

String imageUrl = getIntent().getStringExtra("image_url");
String imageName = getIntent().getStringExtra("image_name");
String array= getIntent().getStringExtra("array_id");

然后我调用setArray(array)了然后在函数内部,我被卡住了。

private void setArray(String array) {
    // Stuck here 
}

我不知道该怎么办。我ListView在第二个布局中设置了一个,并在这个网站上找到了这个代码。

ListView lv = (ListView) findViewById(R.id.extView);
ArrayAdapter<CharSequence> aa = ArrayAdapter.createFromResource(this, R.array.id, android.R.layout.simple_list_item_1);
lv.setAdapter(aa);

哪个有效,如果我将源设置为静态数组 id 但如何将其设置为我收到的字符串?

试过了getString(array),没用。我还需要为onClick这些项目设置一个监听器。

标签: javaandroidarrayslistview

解决方案


要在 a 中显示数组ListView,您需要有一个自定义适配器。ArrayAdapter您当前使用的是用于显示 Android SDK 提供的列表的本机适配器。但是,如果您需要显示ListView从数组中动态填充项目的类,则需要一个自定义类。

为此,您需要有一个如下所示的自定义适配器类。

public class ListAdapter extends ArrayAdapter<String> {

    private int resourceLayout;
    private Context mContext;

    public ListAdapter(Context context, int resource, List<String> items) {
        super(context, resource, items);
        this.resourceLayout = resource;
        this.mContext = context;
    }

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

        View v = convertView;

        if (v == null) {
            LayoutInflater vi;
            vi = LayoutInflater.from(mContext);
            v = vi.inflate(resourceLayout, null);
        }

        String p = getItem(position);

        if (p != null) {
            TextView tt1 = (TextView) v.findViewById(R.id.id);
            tt1.setText(p.getId());
        }

        return v;
    }
}

现在您需要一个布局来指示列表中的每个项目。例如,您的布局名称是list_item.xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content" android:orientation="vertical"
    android:layout_width="fill_parent">

    <TextView
        android:id="@+id/id"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="left"
        android:height="40sp" />
</LinearLayout>

现在在您的第二个Activity中,您需要初始化适配器并在您的适配器中设置适配器,ListView如下所示。请注意,由于适配器采用 a List,您需要将array字符串从 a转换String为 a List,然后将其传递给适配器。

// I assume, the String is comma separated, which indicates the array.
List<String> arrayList = Arrays.asList(array.split("\\s*,\\s*"));

ListView lv = (ListView) findViewById(R.id.extView);
ListAdapter customAdapter = new ListAdapter(this, R.layout.list_item, arrayList);
lv.setAdapter(customAdapter);

希望有帮助!


推荐阅读