List View in Fragment not working

2019-03-02 01:43发布

问题:

Heres my fragment code :

public class LeftFragment extends ListFragment {

ArrayList<String> data;

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    View view = inflater.inflate(R.layout.left_fragment, container, false);

    data = new ArrayList<String>();
    data.add("1. dell");
    data.add("2. samsung");
    data.add("3. apple");
    data.add("4. hp");

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, data);
        setListAdapter(adapter);

    return view;
}

and heres my xml for this fragment:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#FF0000" >

<TextView 
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Heres the list :"/>

<ListView 
    android:id="@android:id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="5dp" />
</LinearLayout>

and

 logcat file says :Binary XML file line #5:error inflating class fragment !!

what my project has is: two fragments left and right. left one should contain the List View,

but wat i hav observed is fragments are working fine when i Dont use "ListView" in xml !! but as i am using it.. left fragment is occupying the space of right fragment as well.

Please help ! thank you !

回答1:

Your error message seems to suggest that the background color is not being read properly. For black try using "#ff000000" or "#ffff0000" for red.



回答2:

Try this:

 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
       return inflater.inflate(R.layout.left_fragment, container, false);
}


    @Override
public void onViewCreated(View view, Bundle savedInstanceState) {
  ArrayList<String> data;  
  data = new ArrayList<String>();
  data.add("1. dell");
  data.add("2. samsung");
  data.add("3. apple");
  data.add("4. hp");

  ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, data);
    setListAdapter(adapter);
 }