【发布时间】:2017-08-04 11:45:30
【问题描述】:
我正在使用 Volley 从网页中获取 JSON 数据,然后处理所述数据并将其添加到 HashMap。之后,我创建了一个 ListAdapter 并将其提供给 HashMap。 所有这一切都有效,我没有收到任何错误,但由于某种原因实际上没有任何显示。
ListView 嵌套在 LinearLayout 片段中,并且适配器使用自定义布局。片段渲染良好。
MainActivity 中的 onCreateView
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.menu_betriebe, container, false);
mitgliederList = new ArrayList<>();
mitgliederListView = view.findViewById(R.id.menu_betriebe_mitglieder_list);
String url = getString(R.string.api_base_url) + "removed";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
JSONArray mitglieder;
try {
mitglieder = response.getJSONArray("data");
for (int i = 0; i < mitglieder.length(); i++) {
JSONObject mitgliedObject = mitglieder.getJSONObject(i);
String mitglied_name = mitgliedObject.getString("mitglied_name");
Log.d("WBV", mitglied_name);
HashMap<String, String> mitglied = new HashMap<>();
mitglied.put("mitglied_name", mitglied_name);
mitgliederList.add(mitglied);
}
ListAdapter adapter = new SimpleAdapter(
getActivity(),
mitgliederList,
R.layout.betriebe_list_item,
new String[]{"mitglied_name"},
new int[]{R.id.betriebe_list_item_mitglied_name});
mitgliederListView.setAdapter(adapter);
} catch (JSONException e) {
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("WBV", "Error: " + error.getMessage());
}
}
);
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, "json_obj_req");
return inflater.inflate(R.layout.menu_betriebe, container, false);
}
片段
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/menu_betriebe"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="@+id/menu_betriebe_mitglieder_list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
列表项布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/betriebe_list_item_mitglied_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:textColor="@color/colorPrimaryDark"
android:textSize="16sp"
android:textStyle="bold"
android:text="HalloTest"/>
</LinearLayout>
【问题讨论】:
-
使用 match_parent 而不是 fill_parent。第二个在 Android 中已弃用
-
你能不能在你的catch块里做一个e.printStackTrace()看看有没有异常
-
在 ListView 中使用 match_parent 而不是 wrap_content
-
按照建议更改为 match_parent,没有变化。 @kapsym 我做了,没有任何东西打印通过日志的 for 循环
-
我认为列表项布局应该只有
而不是在 内尝试一下。
标签: java android listview android-fragments