gpt4 book ai didi

android setOnItemClickListener 无法使用 Intent 传递数据

转载 作者:行者123 更新时间:2023-11-30 02:21:06 25 4
gpt4 key购买 nike

我使用 listview 并重写了 setOnItemClickListener。在 setOnItemClickListener() 中,我使用 intent 将数据传递给另一个 Activity 。但是另一个 Activity 收到空值。代码是:

  1. QuerBook.java(发送数据)

公共(public)类 QueryBook 扩展 Activity {

private List<BookItem> bookList = new ArrayList<BookItem>();
private Bundle saved;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
saved = savedInstanceState;
setContentView(R.layout.querybook);
Log.d("Activity1","haha"+getClass().getSimpleName());
queryBook();
BookAdapter adapter = new BookAdapter(QueryBook.this, R.layout.bookitem, bookList);
ListView listView = (ListView) findViewById(R.id.list_view);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener(){

@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.d("Activity1",getClass().getSimpleName());
// TODO Auto-generated method stub
BookItem bookItem = bookList.get(position);

id = bookItem.getId();
Intent intent = new Intent(QueryBook.this, BookDetail.class);
intent.putExtra("newid",id);
//Log.d("bookid","hah id = "+id);


startActivity(intent);

}
});

2.BookDetail.java(接收数据)公共(public)类 BookDetail 扩展 Activity {

private List<BookItem> bookitemList = new ArrayList<BookItem>();
private int id;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bookdetail);
Log.d("Activity",getClass().getSimpleName());
Intent intent = getIntent();
id = intent.getIntExtra("newid",-1);
Log.d("bookid","book get id is "+id);
}

The 'id' is always return -1;

最佳答案

onItemClick() 中,变量 id 被定义为 long。实际上它是签名中的一个参数:

    public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {

所以当你打电话的时候

intent.putExtra("newid",id);

您实际上是将一个 long 项目放入“extras”包中,而不是一个 int

这就是为什么当您调用 getIntExtra() 时您会得到 -1,因为类型不匹配。

关于android setOnItemClickListener 无法使用 Intent 传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28533217/

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