如何获取listview项目字符串?

时间:2013-06-20 16:51:36

标签: java android listview

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

这是我的代码:

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();
            }
        });
    }
}

但它每次都会关闭。

3 个答案:

答案 0 :(得分: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();
    }
});

答案 1 :(得分:1)

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

答案 2 :(得分: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(); 

                }
        });