我在Fragment中显示带有自定义适配器的listView时遇到问题,此代码在活动中有效,但不在我的片段中,当我运行代码时不显示任何错误。 再次,此代码在活动中起作用,使用适配器正确显示listView,并显示从JsonObjectRequest获得的每个数据的Toast,但在Fragment中,不只显示listView,而是正确显示Toast。我将片段的背景色设置为红色,但是却显示了白色的屏幕和Toast。(对不起,我的英语不好。)
public class ComplaintsFragment extends Fragment {
ListView lstCategories;
private RequestQueue queue;
private String url="http://192.168.1.3:8000/api/tipos";
private ArrayAdapter<CategoriaModel> categoriaAdapter;
List<CategoriaModel> categories;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup
container,@Nullable Bundle savedInstanceState) {
final View view= inflater.inflate(R.layout.fragment_complaints,
container, false);
queue=Volley.newRequestQueue(view.getContext());
categories=new ArrayList<>();
Toast.makeText(view.getContext(), "Hello you're Fragment",
Toast.LENGTH_SHORT).show();
lstCategories=(ListView) view.findViewById(R.id.lstCategories);
JsonObjectRequest jsonObjectRequest = new
JsonObjectRequest(Request.Method.GET, url, null, new
Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int idcategory=jsonObject.getInt("idcategory");
String name = jsonObject.getString("name");
String details= jsonObject.getString("details");
CategoriaModel category=new
CategoriaModel(idcategory,name,details);
Toast.makeText(view.getContext(),
category.toString(), Toast.LENGTH_SHORT).show();
categories.add(category);
}
categoriaAdapter=new
CategoriaAdapter(getActivity(),
android.R.layout.simple_list_item_1,categories);
lstCategories.setAdapter(categoriaAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(jsonObjectRequest);
return view;
}
}
这是我的listView适配器
public class CategoriaAdapter extends ArrayAdapter<CategoriaModel> {
public CategoriaAdapter(@NonNull Context context, int resource, @NonNull List<CategoriaModel> objects) {
super(context, resource, objects);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
CategoriaModel objItem=getItem(position);
LayoutInflater inflater= (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View contenedor=inflater.inflate(R.layout.item_category,parent,false);
TextView lblNombre=contenedor.findViewById(R.id.lblNombre);
TextView lblDescripcion=contenedor.findViewById(R.id.lblDescripcion);
lblNombre.setText(objItem.getNombre());
lblDescripcion.setText(objItem.getDescripcion());
return contenedor;
}
}
答案 0 :(得分:0)
我替换了这个:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new ComplaintsFragment()).commit();
与此:
getSupportFragmentManager().beginTransaction().replace(android.R.content,new ComplaintsFragment()).commit();
所有作品,问题已解决