Android - 如何将项目单击方法添加到ArrayAdapter

时间:2011-11-14 18:18:53

标签: android android-arrayadapter

我有一个简单的ArrayAdapter。我想为列表的每一行单击设置一个监听器,以便打开一个新的Activity。我该怎么办?我的ArrayAdapter代码 -

public class CountryListAdapter extends ArrayAdapter<String> {
private final Activity context;
private final ArrayList<String> names;

public CountryListAdapter(Activity context, ArrayList<String> names) {
    super(context, R.layout.rowlayout, names);
    this.context = context;
    this.names = names;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();
    View rowView = inflater.inflate(R.layout.rowlayout, null, true);
    TextView textView = (TextView) rowView.findViewById(R.id.label);
    textView.setText(names.get(position));
    return rowView;
}

3 个答案:

答案 0 :(得分:10)

假设您使用ListActivity实施OnItemClickListener 你可以使用这段代码:

ArrayAdapter<Object> ad = new ArrayAdapter<Object>(this,
                android.R.layout.simple_list_item_checked, items);
        setListAdapter(ad);
        ListView list = getListView();
        list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        //list.setItemChecked(0, true);
        list.setOnItemClickListener(this);

修改: 否则,如果您不扩展ListActivity,请在布局中使用listview,并将ListView list = getListView()替换为ListView list = findViewById(R.id.listView)之类的内容。将list.setOnItemClickListener(this)替换为

list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            }
        });

答案 1 :(得分:4)

只需实现AdapterView.OnItemClickListener。

@Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
    Intent i = new Intent(this, ProductActivity.class);
    i.putExtra("item_id", manager.getItemIdAtIndex(pos));
    startActivity(i);
}

然后只需将该方法设置为适配器中的onItemClickListener。

答案 2 :(得分:-2)

使用以下方法设置适配器后:

mListView.setAdapter(myCountryListAdapter); 

然后,您可以为列表视图设置点击监听器:

mListView.setOnParentClickListener(new  OnClickListener() {         
    public void onClick(View view,) {
            ///do what you want the click to do
    }       
    });