【问题标题】:Sorting fragments in ListView在 ListView 中对片段进行排序
【发布时间】:2020-03-03 21:18:30
【问题描述】:

我目前正在使用 LinearLayout 来显示片段视图列表,但我希望能够通过片段视图的参数之一对它们进行排序。它恰好是一个文本字段,但它在约束布局内。约束布局是片段的容器。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"

    android:id="@+id/clPostcode"
    ... >
    <TextView
        android:id="@+id/tvPostcodeName"
        ... />
    <TextView
        android:id="@+id/tvPostcodeCity"
        ... />

</androidx.constraintlayout.widget.ConstraintLayout>

使用片段管理器/片段事务将这个片段放置在一个简单的线性布局中。我想按 tvPostcodeName 字段对列表中的片段进行排序。用户会定期向列表中添加新元素,我希望它们按数字顺序排列。

TransactionManager 不能将它们放入要排序的 ArrayAdapter 中。

还有其他选择吗?

【问题讨论】:

    标签: android android-fragments android-arrayadapter


    【解决方案1】:

    通过子类化 ArrayAdapter 解决了这个问题。我必须编写自己的构造函数来使用 FragmentManager 创建片段。

    public FragmentManager(... T[] fragments){
    
        FragmentTransaction ft = activity.getSupportFragmentManager()
                .beginTransaction();
        for (int i = 0; i < fragments.length; i++){
            Fragment fragment = fragments[i];
            //Do what ever you need to do to your fragment instance
            ft.add(fragment, fragment.getSomeUniqueString());
            mObjects.add(fragment);
        }
        ft.commit();
    }
    

    getView 为:

    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        Fragment fragment = mObjects.get(position);
        ... // checking left off to save space
        view = fragment.getRootView();
        ... // checking left off to save space
        return view;
    }
    

    然后排序必须知道片段类的结构。

    我认为也可以通过仅保留 SomeUniqueString 的列表并使用它在 FragmentManager 中查找ViewByTag 来完成。那将是下一个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-09
      • 1970-01-01
      • 2013-07-03
      • 1970-01-01
      • 2015-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多