【发布时间】:2011-11-23 22:31:11
【问题描述】:
我正在尝试通过从onCreateView(LayoutInflater, ViewGroup, Bundle) 返回我自己的视图层次结构来自定义片段布局。这使我的自定义视图膨胀,但似乎堆叠视图而不是在内部膨胀,我一次看到所有内容。任何帮助表示赞赏。
MyActivity.java:
public class MyActivity extends FragmentActivity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) {
ArrayListFragment list = new ArrayListFragment();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, list).commit();
}
}
public static class ArrayListFragment extends ListFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
inflater.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.main, container);
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String List[] = {"Larry", "Moe", "Curly"};
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, List));
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="8dp"
android:paddingRight="8dp">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="THIS IS A BUTTON" />
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00FF00"
android:layout_weight="1"
android:drawSelectorOnTop="false" />
<TextView
android:id="@android:id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF0000"
android:text="No data" />
</LinearLayout>
【问题讨论】:
-
还要注意,我使用的是 android-support-v4。从 android 文档中,它明确指出:“ListFragment 具有由单个列表视图组成的默认布局。但是,如果您愿意,您可以通过从 onCreateView(LayoutInflater, ViewGroup, Bundle) 返回您自己的视图层次结构来自定义片段布局. 为此,您的视图层次结构必须包含一个 ID 为“@android:id/list”的 ListView 对象(如果它在代码中,则为列表)。”
标签: android android-layout android-fragments android-listview android-inflate