0

如何获取我在列表视图中单击的项目?

这是我的代码:

public class MainClass extends Activity {
    ArrayList <String> listItems = new ArrayList<String>();
    ArrayAdapter <String> adapter;
    ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);

        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems);
        listView = (ListView) findViewById(R.id.listView1);
        listView.setAdapter(adapter);
        listItems.add("Item 1");
        listItems.add("Item 2");
        listItems.add("Item 3");
        adapter.notifyDataSetChanged();

        listView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(),
                        listView.getItemAtPosition(0).toString(),
                        Toast.LENGTH_LONG).show();
            }
        });
    }
}

但它每次都强制关闭。

4

3 回答 3

2

改变:

listView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        Toast.makeText(getApplicationContext(),
                listView.getItemAtPosition(0).toString(),
                Toast.LENGTH_LONG).show();
    }
});

至:

listView.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            Toast.makeText(getApplicationContext(), listView.getItemAtPosition(arg2).toString(), Toast.LENGTH_LONG).show();
    }
});
于 2013-06-20T16:54:18.393 回答
1

onItemClickListener如果要与列表中的项目交互,则需要使用 a 。这在方法中有一个位置参数,然后您可以使用它来检索该位置的值。

于 2013-06-20T16:55:06.577 回答
0
try :

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                public  void onItemClick(AdapterView parent,
                        View view, int pos, long id) {




                    String item=(String)((TextView) view).getText();
Toast.makeText(getApplicationContext(),
                        listView.getItemAtPosition(0).toString(),
                        Toast.LENGTH_LONG).show(); 

                }
        });
于 2013-06-20T16:56:57.780 回答