首页 > 解决方案 > 从适配器更新活动编辑文本

问题描述

我有一个MainActivity使用 aRecyclerView和一个Adapter. 我想从课堂上更新Textview标题。当用户在Adapter中单击时。CheckBoxCardViewRecyclerView

单击并获取信息效果很好,但我不知道如何TextView从班级访问标题Adapter以便能够在用户单击复选框并更改信息时随时更新信息。

所以,我的问题是,如何TextViewAdapter课堂上访问标题?

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/fondo"
    android:orientation="vertical"
    tools:context=".Menu_21RutinaMati">

        <TextView
            android:id="@+id/titol"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:background="@color/colorAccent"
            android:gravity="center"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="18sp"
            android:textStyle="bold" />

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recycler_View"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="5dp"/>

</LinearLayout>

标签: android

解决方案


您可以在适配器中定义一个接口:

public interface onItemClickListener{
      void onClick(String title, Long id);//pass your object types.
}

并在适配器中定义此接口并在适配器中初始化

 onItemClickListener onItemClickListner;

      public void setOnItemClickListener(adapter.onItemClickListener 
      onItemClickListner) 
      {
      this.onItemClickListner = onItemClickListner;
      }

在cardview的“onClickListener”方法中,使用接口对象:

holder.cardview.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            onItemClickListner.onClick(model.getTitle(),model.getId());
        }
        });

现在让我们在定义您的适配器对象后进入活动,像这样实现接口方法

    Adapter adapter = new Adapter(context,list);
     adapter.setOnItemClickListener(new adapter.onItemClickListener() {
        @Override
        public void onClick(String title, Long id) {
            txt.setText(title);
           
        }
     });

希望这对你有帮助!


推荐阅读