繁体   English   中英

HashMap上的SimpleAdapter无法正常工作

[英]SimpleAdapter on HashMap does not work properly

我有一个像这样的JSON:

 [{"message":"Hello","id":1,"name":"Hello"},{"message":"James","id":2,"name":"Smith"}]

我用来填充ArrayList<HashMap<String, String>>以便将json的项目显示到ListView中。
这是我当前正在使用的代码:

   private void createListView(){
        for(int i = 0 ; i < json.length() ; i++){
            try{
                JSONObject temp = json.getJSONObject(i);
                HashMap<String, String> map = new HashMap<>();
                map.put("name", temp.getString("name"));
                map.put("message", temp.getString("message"));
                data.add(map);
            }catch (JSONException e){
                e.printStackTrace();
            }
        }

        String[] from = new String[]{"name", "message"};
        int to[] = new int[]{android.R.id.text1};

        ListAdapter adapter = new SimpleAdapter(getBaseContext(), data, android.R.layout.simple_list_item_1, from, to);
        setListAdapter(adapter);
        Log.d("Debug", json.toString());

    }

这段代码几乎可以正常工作,但不是我能做到的。 它仅显示名称字段。

如何修改它以显示消息名称字段?

它仅显示消息字段。

因为使用android.R.layout.simple_list_item_1作为仅包含在具有android.R.id.text1 id的TextView上的行

如何修改它以显示消息和名称字段?

使用android.R.layout.simple_list_item_2作为行的布局并更改to array:

int to[] = new int[]{android.R.id.text1,android.R.id.text2};

更改此行

int to[] = new int[]{android.R.id.text1};

int to[] = new int[]{android.R.id.text1,android.R.id.text2};

希望这对您有帮助。

这行有错误

int to[] = new int[]{android.R.id.text1};

在这里您仅提及一个控件。 我想这是为了传达信息。 您需要为Name添加另一个控件。

使用“ android.R.layout.simple_list_item_2”代替“ android.R.layout.simple_list_item_1”

ListAdapter adapter = new SimpleCursorAdapter(
                 this,
                 android.R.layout.simple_list_item_2,
                 mCursor,     // Pass in the cursor to bind to.
                 new String[] {People.NAME, People.COMPANY}, // Array of cursor columns to bind to.
                 new int[] {android.R.id.text1, android.R.id.text2});  // Parallel array of which template objects to bind to those columns.

         // Bind to our new adapter.
         setListAdapter(adapter);
SimpleAdapter playlistadapter = new SimpleAdapter(getActivity().getApplicationContext(), songsList, R.layout.file_view,
                new String[] { "songTitle","songAlbum", "songartist","songPath" }, new int[] { R.id.checkTextView, R.id.text2, R.id.text3, R.id.text4 });

playlistadapter.setViewBinder(new SimpleAdapter.ViewBinder(){
    boolean setViewValue(View view, Object data, String textRepresentation){
            if(view.getId () == R.id.songartist){
                view.setText("("+textRepresentation+")");
            }
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM