0

次の形式のリモートJSONデータを使用してListViewにデータを入力しています。

{"nodes":[{"node":{"title":"Article#1","id":"4"}},{"node":{"title":"Article#2","id":"3"}}]}

私のListViewは、次のコードで構成されています。

ArrayList<String> articles = new ArrayList<String>();
    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(title);
                    }
                }catch(JSONException j){
                    Log.e("CHECK", "Attempting to read data returned from JSONReader: " + j.toString());
                }
    ListView articlesList = (ListView)findViewById(R.id.articlesList);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(ArticlesActivity.this, R.layout.article_item, R.id.articleItem, articles);
    articlesList.setAdapter(adapter);

プロセス全体が機能し、記事のタイトルが正常に一覧表示されます。しかし、私は各リスト項目でonSelectListenersを有効にするのに役立つチュートリアルに従おうとしています。各記事のタイトルに関連付けられているID要素は、記事のコンテンツをリモートで取得するために必要なすべてです。

タイトルとIDデータの両方を含むようにArrayListを設定し、それを使用して動的なOnSelectListener対応のListViewを設定することは可能ですか?

4

1 に答える 1

0

それを行う適切な方法は、記事の名前とID、および必要な情報を保持するクラスを作成することです。カスタムアダプタでは、ビューを作成するときにsetTag()メソッドを使用します。次に、onClickListenerでgetTag()メソッドを使用します。以下に、いくつかのコードスニップセットが役立つことを願っています。

public class Article{
private String name;
private String id;

public Article(String name, String id) {
    this.name =name;
    this.id = id;

}

    public String getName() {
        return name;
    }

    public String getID() {
        return id;}
}

カスタムアダプタクラスでは、ビューを作成するときにsetTagメソッドを使用します

       public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = inflater.inflate(R.layout.group_list, null);
TextView title = (TextView) v.findViewById(R.id.group_title);
                ...//rest of my code 

                Article article = getItem(position);
                title.setText(article.getName());
                title.setTag(article);
                v.setTag(article);
            return v;
        }

クリックリスナーで

list.setOnItemClickListener(new OnItemClickListener() {

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

                Article article= (Article ) view.getTag();
                String articleID= article.getID();
}
}
于 2013-02-17T00:33:39.650 に答える