gpt4 book ai didi

java - 如何获取listview项目字符串?

转载 作者:行者123 更新时间:2023-12-01 23:45:02 25 4
gpt4 key购买 nike

如何获取我在 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();
}
});
}
}

但它每次都会强制关闭。

最佳答案

更改:

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

关于java - 如何获取listview项目字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17219352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com