通过android中列表项的自定义适配器,通过意图将数据从一个活动发送到另一个活动/片段

通过android中列表项的自定义适配器,通过意图将数据从一个活动发送到另一个活动/片段,android,android-fragments,Android,Android Fragments,我是一名android初学者,我正在制作一个餐厅应用程序,其中包含一个活动中的特许经营城市微调器,如果用户从微调器中选择一个城市并单击按钮,它将在另一个活动/片段中显示所选城市的餐厅列表。如何通过自定义适配器实现此目的???要实现此目的,请执行以下操作: 步骤1:当用户点击OK按钮时,表示 okButton.setOnClickListener(new View.OnClickListener) { @Override public void onClick(View v) { String

我是一名android初学者,我正在制作一个餐厅应用程序,其中包含一个活动中的特许经营城市微调器,如果用户从微调器中选择一个城市并单击按钮,它将在另一个活动/片段中显示所选城市的餐厅列表。如何通过自定义适配器实现此目的???

要实现此目的,请执行以下操作:

步骤1:当用户点击OK按钮时,表示

okButton.setOnClickListener(new View.OnClickListener) {

@Override
public void onClick(View v) {
String selectedValue = spinner.getSelectedItem();
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("selectedCity", selectedValue);
startActivity(intent);
}
});
步骤2:现在进入secondActivity oncreate

@凌驾

public void onCreate(Bundle s) {
setContentView(R.layout.b);

Intent intent = getIntent();
if(intent != null) {
intent.getStringExtra("selectedCity");
}
}

就这样!!!全部完成。

答案包括两部分:

从第一个活动的微调器中获取所选城市ID,并将其发送到第二个活动中。对于这一部分,您可以参考@Chaitanya的答案,使用intent在两个活动之间传递信息

本部分介绍如何处理选定的城市值。关于你的问题,你必须获得基于该城市的餐厅列表,并将其置于列表视图或循环视图中。您必须编写适当的代码,才能从数据库或web服务中获取基于城市的reastaurant列表。之后,只需将列表传递到第二个活动中的此处,其中实现了listview:

ListView yourListView = (ListView) findViewById(R.id.itemListView);
ListAdapter customAdapter = new ListAdapter(this, R.layout.itemlistrow, <<restaurantList>>);
yourListView .setAdapter(customAdapter);
示例适配器

public class ListAdapter extends ArrayAdapter<Item> {

public ListAdapter(Context context, int textViewResourceId) {
    super(context, textViewResourceId);
}

public ListAdapter(Context context, int resource, List<Item> items) {
    super(context, resource, items);
}

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

    View v = convertView;

    if (v == null) {
        LayoutInflater vi;
        vi = LayoutInflater.from(getContext());
        v = vi.inflate(R.layout.itemlistrow, null);
    }

    Item p = getItem(position);

    if (p != null) {
        TextView tt1 = (TextView) v.findViewById(R.id.id);
        TextView tt2 = (TextView) v.findViewById(R.id.categoryId);
        TextView tt3 = (TextView) v.findViewById(R.id.description);

        if (tt1 != null) {
            tt1.setText(p.getId());
        }

        if (tt2 != null) {
            tt2.setText(p.getCategory().getId());
        }

        if (tt3 != null) {
            tt3.setText(p.getDescription());
        }
    }

    return v;
}
}


这是我在项目中使用的一个类。你需要有一个你想要展示的物品的集合,在你的例子中是餐馆。您需要覆盖View getViewint position、View convertView、ViewGroup parent方法。

为什么需要自定义适配器?自定义适配器是什么意思?在此处编写代码?意图足以将所选城市id发送给另一个城市activity@xFighter因为所选城市的餐厅列表可以是1个或10个以上,所以我需要适配器在列表视图中显示这些。谢谢,我将通过intent传递所选城市,以便填充列表。我可以使用适配器实现这一点吗?因为餐厅列表可能会有所不同?如果是这样,那么你能告诉我如何使用适配器和活动之间的接口吗。当列表发生变化时,请使用界面通知活动。谢谢,我得到了结果,当我单击列表项时,是否有任何方式可以通过intent将我带到以下餐厅地址