gpt4 book ai didi

Android setonitemclicklistener实现

转载 作者:行者123 更新时间:2023-11-29 18:02:51 24 4
gpt4 key购买 nike

我有一个 ArticlesAdapter,我用它来读取远程 JSON 数据。适配器正在工作,但我正在努力让我的 ListView setonitemclicklister 工作。

我想要完成的是点击 ListItem 并获取所点击选项的文章数据的能力。我的 Article 类中有像 getName() 这样的函数,我需要调用它来响应 ListItem 单击,但我似乎找不到实现它的方法。

我正尝试在我的 AsyncTask 类中执行此操作。

使用以下代码:

protected void onPostExecute(JSONArray result) {
// TODO Auto-generated method stub

Log.i("CHECK", "RESULTS: " + result);

List<Article> articles = new ArrayList<Article>();

String title = null;
String nid = null;

try{
for(int i=0; i < data.length(); i++){
JSONObject dataObj = (JSONObject)data.get(i);
JSONObject record = dataObj.getJSONObject("node");
title = (record.getString("title"));
nid = (record.getString("nid"));

Log.i("FOUND", "title: " + title);
Log.i("FOUND", "nid: " + nid);

articles.add( new Article(title, "", Integer.parseInt(nid)) );
}
}catch(JSONException j){
Log.e("CHECK", "Attempting to read data returned from JSONReader: " + j.toString());
}

ListView articlesList = (ListView)findViewById(R.id.articlesList);
ArticleAdapter adapter = new ArticleAdapter(ArticlesActivity.this, R.layout.article_item, articles);
articlesList.setAdapter(adapter);

articlesList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "testing : ", Toast.LENGTH_LONG);
Log.i("CHECK", "AdapterView: " + parent);
Log.i("CHECK", "VIEW : " + view);
Log.i("CHECK", "POSITION : " + position);
Log.i("CHECK", "ID : " + id);
}
});

if(dialog.isShowing())
dialog.dismiss();
}

我的问题是我不确定如何让 setOnItemClickListener 工作。我可以通过 Log 函数打印参数:

Log.i("CHECK", "AdapterView: " + parent);
Log.i("CHECK", "VIEW : " + view);
Log.i("CHECK", "POSITION : " + position);
Log.i("CHECK", "ID : " + id);

...但是当我尝试将任何参数转换为 Article 对象以便调用它的 getName() 函数等时出现错误。

最佳答案

您的 AsyncTask 似乎嵌套在您的 Activity 中,如果它不是简单地将 articles 传递给您的 Activity,则使用:

articlesList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
Article article = articles.get(position);
// Do something with article
}
});

关于Android setonitemclicklistener实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14969550/

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