Android setonitemclicklistener实现

时间:2013-02-19 23:27:02

标签: android android-asynctask onclicklistener

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

我想要完成的是能够点击ListItem并获取点击选项的文章数据。 我的文章类中有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()函数等。

2 个答案:

答案 0 :(得分:3)

您的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
    }
}); 

答案 1 :(得分:0)

您希望进行的体系结构更改是将ListViewAdapterOnItemClickListener初始化从AsyncTask中提取出来,并仅将articles更新为并通知Adapter回调中的onPostExecute