【问题标题】:Custom ListView in ListFragment or Fragment?ListFragment 或 Fragment 中的自定义 ListView?
【发布时间】:2014-10-16 03:29:33
【问题描述】:

我正在开发一个简单的应用程序,因此主要活动有两个片段,用户可以通过滑动进入。在其中一个上,我想要自定义列表。例如,像https://github.com/JakeWharton/SwipeToDismissNOA 这样的东西,列表中的每个项目都可以通过滑动删除。我能够让一个常规列表在 ListFragment 中工作,但无法让这个自定义列表工作。据我了解, ListFragment 需要有一个简单的 .xml ,但我想使用的那个有更多的东西。像这样的:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:baselineAligned="false"
android:padding="16dp">

<LinearLayout android:layout_width="0dp"
    android:layout_weight="1"
    android:layout_height="match_parent"
    android:layout_marginLeft="8dp"
    android:orientation="vertical">

    <TextView android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="?android:listSeparatorTextViewStyle"
        android:text="ListView" />

    <ListView
        android:id="@android:id/list"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="0dp" />
</LinearLayout>

因此,当我尝试使用此 .xml 获取列表视图()时,它要么返回 null,要么当我尝试执行以下操作时: 查看视图 = inflater.inflate(R.layout.fragment_section_dummy, null); ListView ls = (ListView) view.findViewById(android.R.id.list);

它抛出这个错误: 10-15 20:25:28.895: E/AndroidRuntime(8081): java.lang.UnsupportedOperationException:AdapterView 不支持 addView(View, LayoutParams)。

谢谢。

【问题讨论】:

    标签: android xml listview fragment


    【解决方案1】:

    对我来说,使用我自己的 ID 是最简单的工作,因此我会将您的 ListView ID 更改为另一个 ID。例如,我选择android:id="@+id/myList"

    在您的片段中,在您的 onCreateView 方法中,尝试扩充您的布局并通过 ID 获取您的视图。

     @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.yourDummyLayout, container, false);
    
    
            //You should get your ListView there
            ListView yourListView = rootView.findViewById(R.id.myList);
    
            [......]
    
            return rootView;
        }
    

    试试这个;)祝你好运!

    【讨论】:

      猜你喜欢
      • 2015-02-18
      • 2013-07-22
      • 2015-02-09
      • 1970-01-01
      • 1970-01-01
      • 2015-10-02
      • 1970-01-01
      • 2015-03-07
      • 1970-01-01
      相关资源
      最近更新 更多