gpt4 book ai didi

android - 如何处理android中Listview中的点击事件?

转载 作者:IT王子 更新时间:2023-10-28 23:55:47 26 4
gpt4 key购买 nike

下面是我创建 ListView 的测试代码, ListView 显示成功,但是点击事件有错误。我想创建一个向新 Activity 发送硬编码消息的 Intent 。但是,它显示该行的错误

Intent intent = new Intent(context, SendMessage.class);

那么,问题是,我应该为这门课提供什么?

另外,如何在 ListView 行中捕获数据并传递给新 Activity ,而不是对输出消息进行硬编码?例如BBB,AAA,R.drawable.tab1_hdpi 为第一行。

谢谢。

public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.ListViewTest.MESSAGE";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<ListEntry> members = new ArrayList<ListEntry>();
members.add(new ListEntry("BBB","AAA",R.drawable.tab1_hdpi));
members.add(new ListEntry("ccc","ddd",R.drawable.tab2_hdpi));
members.add(new ListEntry("assa","cxv",R.drawable.tab3_hdpi));
members.add(new ListEntry("BcxsadvBB","AcxdxvAA"));
members.add(new ListEntry("BcxvadsBB","AcxzvAA"));
members.add(new ListEntry("BcxvBB","AcxvAA"));
members.add(new ListEntry("BvBB","AcxsvAA"));
members.add(new ListEntry("BcxvBB","AcxsvzAA"));
members.add(new ListEntry("Bcxadv","AcsxvAA"));
members.add(new ListEntry("BcxcxB","AcxsvAA"));
ListView lv = (ListView)findViewById(R.id.listView1);
Log.i("testTag","before start adapter");
StringArrayAdapter ad = new StringArrayAdapter (members,this);
Log.i("testTag","after start adapter");
Log.i("testTag","set adapter");
lv.setAdapter(ad);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent intent = new Intent(context, SendMessage.class);
String message = "abc";
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
});
}

最佳答案

我看不到你在哪里声明 context。为了创建 Intent ,您可以使用 MainActivity.this

 lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent intent = new Intent(MainActivity.this, SendMessage.class);
String message = "abc";
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
});

要在单击后检索对象,您可以使用 AdapterView:

ListEntry entry = (ListEntry) parent.getItemAtPosition(position);

关于android - 如何处理android中Listview中的点击事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17851687/

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