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

前端之家收集整理的这篇文章主要介绍了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;
}

解决方法

假设您正在使用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 = findViewById(R.id.listView)替换ListView list = getListView().用.替换list.setOnItemClickListener(this)

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

            }
        });

猜你在找的Android相关文章