java - 如何将值从适配器传递到另一个类

标签 java android

我正在尝试从项目 View 获取开关状态

这是保存开关的布局文件,我想知道是否从另一个类检查开关

我想在适配器中执行此操作,并通过检查是否选中开关将值从适配器传递到另一个类,或者从类获取布局并检查是否选中开关

<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);
        }
    }
}

最佳答案

使用共享首选项

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

存储数据

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

获取数据

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

关于java - 如何将值从适配器传递到另一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61797621/

相关文章:

Java CompletableFuture thenCompose 与几个异步任务

android - Robotium:请安装兼容的 Android API 级别(15 或更高)

android - 在android模拟器中运行应用程序时出错

java - 糟糕的 : Suggest design for the following scenario

java - J2ME中如何生成哈希值?

java - 我的 GUI 没有完全显示

java - 为什么 Java 有 4 种不同类型的引用?

android - 如何将 LinearLayout 中的两个 TextView 对齐在同一行

android - 使用 Kotlin Android Extensions 以编程方式扩展布局

android - 如何在 Android 中设计同步服务