【发布时间】:2019-07-03 05:43:18
【问题描述】:
我有一个 ListFragment 在 XML 文件资源中没有 ListView 标记的情况下工作。
根据以下参考,ListFragment 需要一个带有ListView 标签的 XML 文件:
https://developer.android.com/reference/android/app/ListFragment
但是,下面的代码在没有代码的情况下也能正常工作。这个帖子解释了原因吗?
Difference between android.app.Fragment and android.support.v4.app.Fragment
另外,我正在使用 android-support-v4-app-fragment 和 android-app-fragment。
谢谢。
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">
<FrameLayout
android:id="@+id/newFrame"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary">
</FrameLayout>
</LinearLayout>
主活动:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment fragmentA = new FragmentA();
fragmentTransaction.add(R.id.newFrame, fragmentA, "fragmentA");
fragmentTransaction.commit();
}
}
列表片段:
public class FragmentA extends ListFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String dataArray[] = new String[]{"One", "Two", "Three",};
ListAdapter listAdapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, dataArray);
setListAdapter(listAdapter);
}
}
【问题讨论】:
-
因为它有一个 ListView 作为
android.R.id.list我想。
标签: android android-fragments android-listfragment