【问题标题】:Refreshing content of RecyclerView in a TabLayout刷新 TabLayout 中 RecyclerView 的内容
【发布时间】:2019-08-19 14:58:49
【问题描述】:

我有一个带有 tabLayout 和 recyclerView 的片段。当用户选择一个选项卡时,我希望 recyclerView 使用方法 refreshList() 更改其内容。 默认情况下,第一个选项卡被选中,当我选择第二个选项卡时,内容会发生变化。但是当我再次选择第一个时,它不再改变内容了。

这是我的课:

public class SearchFragment extends Fragment {

    private RecyclerView recView;
    private View view;
    private FloatingActionButton fab;
    private TabLayout tabLayout;
    private OwnAdapter ownAdapter;

    final int MY_PERMISSIONS_REQUEST_EXTERNAL_STORAGE = 1;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.search_fragment, container, false);
        recView = view.findViewById(R.id.file_list);
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        recView.setLayoutManager(manager);
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recView.getContext(),
                manager.getOrientation());
        recView.addItemDecoration(dividerItemDecoration);
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                    Manifest.permission.READ_EXTERNAL_STORAGE)) {
            } else {
                ActivityCompat.requestPermissions(getActivity(),
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_REQUEST_EXTERNAL_STORAGE);
            }
        }
        refreshList("/sdcard/");
        fab = view.findViewById(R.id.fab_search);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        tabLayout = view.findViewById(R.id.tabLayout);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                System.out.println(tab.getPosition());
                switch(tab.getPosition()){
                    case 0:
                        refreshList("/sdcard/");
                    case 1:
                        refreshList("/storage/0000-0000/");
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {}

            @Override
            public void onTabReselected(TabLayout.Tab tab) {}
        });
        return view;
    }

    private void refreshList(String s){

        File file = new File(s);
        File[] files = file.listFiles();
        ArrayList<File> itemArrayList = new ArrayList<>();
        try {
            for (int i = 0; i < files.length; i++) {
                if(files[i].isFile()){
                    itemArrayList.add(files[i]);
                }else{
                    itemArrayList.add(files[i].getAbsoluteFile());
                }
            }
        }catch(RuntimeException e){

        }

        String[] itemNames = new String[itemArrayList.size()];
        for(int j = 0; j < itemNames.length; j++){
            itemNames[j] = itemArrayList.get(j).getName();
        }
        ownAdapter = new OwnAdapter(itemNames);
        recView.setAdapter(ownAdapter);
    }
}

适配器类:

public class OwnAdapter extends RecyclerView.Adapter {

    private String[] dataset;

    // Provide a reference to the views for each data item
    // Complex data items may need more than one view per item, and
    // you provide access to all the views for a data item in a view holder
    public static class MyViewHolder extends RecyclerView.ViewHolder {
        // each data item is just a string in this case
        public TextView textView;
        public MyViewHolder(TextView v) {
            super(v);
            textView = v;
        }
    }

    // Provide a suitable constructor (depends on the kind of dataset)
    public OwnAdapter(String[] myDataset) {
        dataset = myDataset;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        TextView v = (TextView) LayoutInflater.from(parent.getContext())
                .inflate(R.layout.textview_for_files, parent, false);

        MyViewHolder vh = new MyViewHolder(v);
        return vh;

    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        // - get element from your dataset at this position
        // - replace the contents of the view with that element
        MyViewHolder holder1 = (MyViewHolder) holder;
        holder1.textView.setText(dataset[position]);

    }

    @Override
    public int getItemCount() {
        return dataset.length;

    }
}

还有布局:

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingRight="6dp"
    android:paddingLeft="6dp">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout_editor_absoluteX="6dp">

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/internal_storage" />

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/sd_card" />

    </com.google.android.material.tabs.TabLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/file_list"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:paddingLeft="6dp"
        android:paddingRight="6dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tabLayout"
        tools:layout_editor_absoluteX="6dp"></androidx.recyclerview.widget.RecyclerView>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab_search"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="@dimen/fab_margin"
        android:layout_marginBottom="@dimen/fab_margin"
        app:fabSize="normal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:srcCompat="@drawable/add" />

</androidx.constraintlayout.widget.ConstraintLayout>

【问题讨论】:

    标签: android android-recyclerview android-tablayout


    【解决方案1】:

    您可以尝试在 refreshList() 方法的末尾添加 ownAdapter.notifyDataSetChanged();。您可能还需要在您的 refreshList() 方法开始时清除您的适配器。如果这些不起作用,This solution 可能会给你一个很好的答案。

    【讨论】:

    • 不管用,但没想到别的,因为每次都新建一个Adapter,调用setAdapter()方法。使用调试器,我还可以看到这没问题。奇怪的是,当我从第一个选项卡移动到第二个选项卡时,内容会发生变化,但只是第一次。之后,我可以选择任何选项卡,但没有任何反应。
    【解决方案2】:

    我使用调试器进行了更多测试,发现当我按下第一个选项卡时,refreshList() 方法被调用了两次。之后的结果是我犯了一个愚蠢的错误。我忘记了 switch-case 语句中的中断! 不过,ownAdapter.notifyDataSetChanged() 不是必需的。

    【讨论】:

    • 好的,现在删除该问题,因为它与您的问题无关。
    猜你喜欢
    • 2020-03-17
    • 2012-06-13
    • 2012-09-16
    • 1970-01-01
    • 2018-12-05
    • 2017-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多