【问题标题】:Android JSONObject to ListViewAndroid JSONObject 到 ListView
【发布时间】:2014-04-25 23:27:41
【问题描述】:

我在这里遇到了问题,我对此完全陌生。

我尝试做的是将 JSONObject 传递给我的适配器并在我的适配器内为该 ListView 创建所有行

这是我的代码:

    private static final String TAG_OS = "android";

    protected void onPostExecute(JSONObject json) {

        try {

            JSONArray jArray = json.getJSONArray(TAG_OS);
            if (jArray != null) {
                for (int i=0;i<jArray.length();i++){
                    listdata.add(jArray.get(i).toString());
                }
            }

            menu_list=(ListView)findViewById(R.id.menu_list);

                MenuAdapter adapter = new MenuAdapter(MainActivity.this, new ArrayList[] {listdata} );
                menu_list.setAdapter(adapter);

        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

我的适配器是这个:

public class MenuAdapter extends ArrayAdapter<ArrayList> {
    private final Context context;
    private final ArrayList[] values;
public MenuAdapter(Context context,ArrayList[] values) {
    super(context, R.layout.menu_main, values);
    this.context = context;
    this.values = values;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater.inflate(R.layout.menu_main, parent, false);

    if (position % 2 == 1) {
        rowView.setBackgroundColor(Color.RED);
    } else {
        rowView.setBackgroundColor(Color.BLUE);
    }

    return rowView;
}

我仍然不知道如何填充整个 ListView,它只是一个具有备用背景的 TextView。我还不明白如何设置一行又一行,还没有找到一个很好的例子。

我该如何解决这个问题? :s

【问题讨论】:

    标签: android listview android-listview android-arrayadapter jsonobject


    【解决方案1】:

    由于您在代码中仅使用单个文本字段,因此您无需为此创建自定义适配器,因为您可以使用 Android 的 ArrayAdapter

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
              android.R.layout.simple_list_item_1, android.R.id.text1, listdata.toArray());
    
    menu_list.setAdapter(adapter);
    

    这个 sn-p 使用默认的 Android 列表布局和一个 TextView,它将负责为您添加多行。

    编辑: 看起来您需要使用 BaseAdapter,因为您需要创建一个扩展 BaseAdapter 的类并使用 ViewHolder,看看我写的这个博客 androidadapternotifiydatasetchanged.blogspot.in,它有一个扩展 BaseAdapter 的类,它使用自定义布局 (.xml) 文件,您将大致了解它是如何完成的

    【讨论】:

    • 现在是的,只是一个文本视图,但需要设置备用背景颜色。可能还有其他元素,例如其他行的图像和按钮
    • 为此,您需要创建一个扩展 BaseAdapter 的类并使用 ViewHolder,看看我写的这个博客 androidadapternotifiydatasetchanged.blogspot.in,它有一个扩展 BaseAdapter 的类,它使用自定义布局( .xml) 文件,您将大致了解它是如何完成的。
    • 如果此答案解决了您的问题,请标记为已接受,这样做有助于其他有相同问题的人快速找到正确答案。
    • 请更新答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多