簡體   English   中英

如何將值從適配器傳遞到另一個 class

[英]How to pass value from adapter to another class

我正在嘗試從項目視圖中獲取開關 state

這是包含開關的布局文件,我想知道是否從另一個 class 檢查開關

我想在適配器中執行此操作並將值從適配器傳遞到另一個 class 通過檢查是否檢查開關或從 class 獲取布局並檢查是否檢查開關

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp">

    <TextView
        android:id="@+id/studentName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Student Name"
        android:textSize="25dp"/>

    <Switch
        android:id="@+id/attendanceSwitch"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="25dp"
        android:checked="true"/>

</RelativeLayout>

這是我的適配器

public class StudentAdapter extends RecyclerView.Adapter<StudentAdapter.ViewHolder> {

    private Context context;
    private List<User> users;
    public StudentAdapter(Context context, List<User> users) {
        this.context = context;
        this.users = users;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.student_item, parent, false);
        return new StudentAdapter.ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
        final User user = users.get(position);


        holder.studentName.setText(user.getStudentname() + " " + user.getLastname());

    }

    @Override
    public int getItemCount() {
        return users.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public TextView studentName;
        public Switch aSwitch;

        public ViewHolder(View itemView) {
            super(itemView);

            studentName = itemView.findViewById(R.id.studentName);
            aSwitch = itemView.findViewById(R.id.attendanceSwitch);
        }
    }
}

使用 SharedPreferences

public SharedPreferences sharedpreferences = getSharedPreferences("mySharedPreferences", MODE_PRIVATE);
public SharedPreferences.Editor PrefsEditor = sharedpreferences.edit();

存儲數據

PrefsEditor.putString("value", "MyString").apply();

獲取數據

String value = sharedpreferences.getString("value", "");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM