main.xml文件
<LinearLayout 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"
android:orientation="horizontal"
android:baselineAligned="false"
tools:context="${relativePackage}.${activityClass}" >
<fragment
android:name="com.example.listfragmentexample.Fragment1"
android:id="@+id/fragment1"
android:layout_weight="0.5"
android:layout_width="0dp"
android:layout_height="200dp" />
<fragment
android:name="com.example.listfragmentexample.Fragment1"
android:id="@+id/fragment2"
android:layout_weight="0.5"
android:layout_width="0dp"
android:layout_height="300dp" />
</LinearLayout>
Fragment1.java
package com.example.listfragmentexample;
import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class Fragment1 extends ListFragment{
String[] presidents = {
"Dwight D. Eisenhower",
"John F. Kennedy",
"Lyndon B. Johnson",
"Richard Nixon",
"Gerald Ford",
"Jimmy Carter",
"Ronald Reagan",
"George H. W. Bush",
"Bill Clinton",
"George W. Bush",
"Barack Obama"
};
/* (non-Javadoc)
* @see android.app.ListFragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment1, container,false);
}
/* (non-Javadoc)
* @see android.app.ListFragment#onListItemClick(android.widget.ListView, android.view.View, int, long)
*/
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(),
"You have selected " + presidents[position],
Toast.LENGTH_SHORT).show();
}
/* (non-Javadoc)
* @see android.app.ListFragment#onViewCreated(android.view.View, android.os.Bundle)
*/
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
}
/* (non-Javadoc)
* @see android.app.Fragment#onCreate(android.os.Bundle)
*/
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, presidents));
}
}
Fragment1.xml
<?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" >
<ListView
android:id="@id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:drawSelectorOnTop="false"/>
</LinearLayout>