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

How to save spanCount of RecyclerView on Shared Preferences?

我的问题是有没有办法在 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 不显示任何内容且按钮不起作用。 如果有人可以帮助我,我将不胜感激......谢谢

你在这里做错了几件事。

Incorrect use of SharedPreferences

Adapter on RecycleView not setup

Manage LinearLayout and StaggeredGridLayoutManager

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

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_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

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

    <Button
        android:padding="8dp"
        android:layout_margin="16dp"
        android:layout_gravity="end|bottom"
        android:id="@+id/buttonPanel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        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_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_margin="8dp">

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

</LinearLayout>

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

编码愉快!