如何在共享首选项上保存 RecyclerView 的 spanCount?

Posted

技术标签:

【中文标题】如何在共享首选项上保存 RecyclerView 的 spanCount?【英文标题】:How to save spanCount of RecyclerView on Shared Preferences? 【发布时间】:2020-12-05 01:36:33 【问题描述】:

我的问题是有没有办法在 SharedPreferences 中保存 ReciclerView 的 SpamCount? 我尝试制作一个可以将视图从“列表模式”更改为“网格模式”的列表,并将该信息保存在 SharedPreferences 中,以便在终止应用程序后保留“列表视图”。 我正在尝试做的示例如下... example of what i try to do on button click

我尝试更改的代码如下...


public class MainActivity extends AppCompatActivity implements View.OnClickListener 

    private static RecyclerView recyclerView;   
    private ReciclerAdapter reciclerAdapter;
    ImageView viewGridS, viewListS;

    SharedPreferences vSettings;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recicler_main);


        vSettings =  this.getSharedPreferences("Vision", 0);

        notesRecyclerView = findViewById(R.id.recycler_view);
        notesRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
        viewListS = findViewById(R.id.viewList);
        viewGridS = findViewById(R.id.viewGrid);


    @Override
    public void onClick(View v) 
        SharedPreferences vSettings =  this.getSharedPreferences("Vision", 0);
        SharedPreferences.Editor viEdit = vSettings.edit();

        switch (v.getId())
        
            case R.id.viewList:
                viewGridS.setVisibility(View.GONE);
                viewListS.setVisibility(View.VISIBLE);
                viEdit.putString("Vision",listView());
                viEdit.apply();
                break;
            case R.id.viewGrid:
                viewListS.setVisibility(View.GONE);
                viewGridS.setVisibility(View.VISIBLE);
                listWiew();
                viEdit.putString("Vision",gridView());
                viEdit.apply();
                break;
          
     );
    

    public int gridView()
          notesRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
        return null;
     

    public int listView()
          notesRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(1,StaggeredGridLayoutManager.VERTICAL));
        return null;
     


当尝试启动 Activity 时,RecyclerView 不显示任何内容并且按钮不起作用。 如果有人可以帮助我,我会提前感谢...谢谢

【问题讨论】:

您没有向适配器提供任何数据,并且您的适配器也未在回收站视图中设置。这就是列表为空的原因。制作列表后,请确保在这两种情况下都没有保存 null。我也认为你的 onCreate 的右花括号在这里丢失了。 【参考方案1】:

你在这里做错了几件事。

SharedPreferences的错误使用

RecycleView 上的适配器未设置

管理LinearLayoutStaggeredGridLayoutManager

我将尝试完成您正在寻找的类似最终结果,一个简单的按钮,在点击时切换布局。代码如下-

MainActivity.java

public class MainActivity extends AppCompatActivity 

    private String LIST_VIEW = "List View";
    private String GRID_VIEW = "Grid View";
    private RecyclerView recyclerView;
    private LinearLayoutManager linearLayoutManager;
    private StaggeredGridLayoutManager staggeredGridLayoutManager;
    private SharedPreferences sharedPreferences;
    private RecycleViewAdapter recycleViewAdapter;


    @Override
    protected void onCreate(final Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //Simple List setup for data to show in recycle view
        List<String> stringList = new ArrayList<>();
        stringList.add("Monday\nI'll ask her out.");
        stringList.add("Tuesday");
        stringList.add("Wednesday\nI'll take her to garden to talk.");
        stringList.add("Thursday\nI'll give her a gift");
        stringList.add("Friday");
        stringList.add("Saturday");
        stringList.add("Sunday\nI'll propose her. ");

        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

        recyclerView = findViewById(R.id.recycler_view);
        recycleViewAdapter = new RecycleViewAdapter(this, stringList);
        
        linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        
        staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        
        /*
        * SharedPreferences value will be null for very first install of app
        * ELSE SharedPreferences will have use last saved value
        * */
        
        String CURRENT_VIEW = sharedPreferences.getString("LAYOUT_TYPE", null);
        if (CURRENT_VIEW == null) 
            CURRENT_VIEW = LIST_VIEW;
            sharedPreferences.edit().putString("LAYOUT_TYPE", LIST_VIEW).apply();
            recyclerView.setLayoutManager(linearLayoutManager);
            recyclerView.setAdapter(recycleViewAdapter);
         else
            switchView(CURRENT_VIEW);

        Button buttonPanel = findViewById(R.id.buttonPanel);
        buttonPanel.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                if(sharedPreferences.getString("LAYOUT_TYPE", null).equals(LIST_VIEW))
                    switchView(GRID_VIEW);
                else
                    switchView(LIST_VIEW);
            
        );
    

    /*
    * Method will switch Layout on RecycleView and update new Adapter
    * @param: Required Layout Type (LIST_VIEW or GRID_VIEW)
    * */
    private void switchView(String layoutTypeValue) 
        if (layoutTypeValue.equals(LIST_VIEW))
            recyclerView.setLayoutManager(linearLayoutManager);
        else if (layoutTypeValue.equals(GRID_VIEW))
            recyclerView.setLayoutManager(staggeredGridLayoutManager);

        sharedPreferences.edit().putString("LAYOUT_TYPE", layoutTypeValue).apply();
        recyclerView.setAdapter(recycleViewAdapter);
    

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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_
    android:layout_
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_
        android:layout_/>

    <Button
        android:padding="8dp"
        android:layout_margin="16dp"
        android:layout_gravity="end|bottom"
        android:id="@+id/buttonPanel"
        android:layout_
        android:layout_
        android:textColor="@android:color/white"
        android:background="@android:color/holo_orange_dark"
        android:text="Change Layout"/>
</FrameLayout>

RecycleViewAdapter.java

public class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewAdapter.CustomViewHolder> 

    private Context context;
    private List<String> stringList;

    public RecycleViewAdapter(Context context, List<String> stringList) 
        this.context = context;
        this.stringList = stringList;
    

    @NonNull
    @Override
    public CustomViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) 
        return new CustomViewHolder(LayoutInflater.from(context).inflate(R.layout.recycle_item_layout, parent, false));
    

    @Override
    public void onBindViewHolder(@NonNull CustomViewHolder holder, int position) 
        holder.textView.setText(stringList.get(position));
    

    @Override
    public int getItemCount() 
        return stringList.size();
    

    public class CustomViewHolder extends RecyclerView.ViewHolder 

        private TextView textView;

        public CustomViewHolder(@NonNull View itemView) 
            super(itemView);
            textView = itemView.findViewById(R.id.text);
        
    

recycle_item_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_
    android:layout_
    android:orientation="vertical"
    android:layout_margin="8dp">

    <TextView
        android:id="@+id/text"
        android:layout_
        android:layout_
        android:padding="16dp"
        android:background="@android:color/holo_blue_dark"
        android:textColor="@android:color/white"
        android:textSize="24sp" />

</LinearLayout>

上面的代码会给你以下结果 -

编码愉快!

【讨论】:

你太棒了!谢谢!!!!这对我有用,我忘了在我的代码上添加适配器

以上是关于如何在共享首选项上保存 RecyclerView 的 spanCount?的主要内容,如果未能解决你的问题,请参考以下文章

如何以共享首选项保存图像?

如何将 HashMap 保存到共享首选项?

如何在单击按钮时将按钮颜色保存到共享首选项?

如何使用共享首选项? [复制]

如何使用 dart/flutter 中的共享首选项保存和获取列表列表

如何保存和获取存储在共享首选项中的包名称?