片段中的Listview没有扩展ListFragment

时间:2015-06-29 10:27:10

标签: android listview android-fragments

扩展ListFragment 时,我没有使用ListView。但是我希望扩展Fragment (而不是ListFragment)。我该怎么办?

public class ListEnployees extends ListFragment {

private Cursor employees;
private MyDatabase db;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    db = new MyDatabase(getActivity());
    employees = db.getEmployees();
    // no more this
    // setContentView(R.layout.list_fruit);

    setListAdapter(new ArrayAdapter<String>(this, R.layout.list_fruit,employees));

    ListView listView = getListView();
    listView.setTextFilterEnabled(true);

    listView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // When clicked, show a toast with the TextView text
            Toast.makeText(getApplicationContext(),
            ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
        }
    });

}

}

3 个答案:

答案 0 :(得分:1)

试试这个,

public class ListEnployees extends Fragment{

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,   Bundle savedInstanceState) {
View parentView = inflater.inflate(R.layout.your_fragment_with_list view, container, false);
ListView list = (ListView) parentView .findViewById(R.id.ur_list);
Adapter adapter = new Adapter(getActivity(),object you want to pass);
list.setAdapter(adapter);
return parentView;
}

}

答案 1 :(得分:1)

试试这个,它对我有用!

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_lista, container, false);

    ListView lst = (ListView) rootView.findViewById(R.id.lst);
    Adapter adapter = //youradapter;
    lst.setAdapter(adapter);

    return rootView;
}

答案 2 :(得分:0)

使用代码:

  public class MainActivity extends Activity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            ListView lst=(ListView) findViewById(R.id.listView1);
            lst.setAdapter(...)
        }
    }


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" >
    </ListView>

</RelativeLayout>