androidstudio recyclerview 和自定义对话框

如何解决androidstudio recyclerview 和自定义对话框

我想创建一个带有回收站视图的自定义对话框。如果我选择回收器视图单元格并在对话框中按确定按钮,则文本视图将更改。我创建了回收器视图适配器、自定义对话框,但我不知道如何连接对话框和适配器以及在 onClick 函数中放入什么..请帮帮我..

custom_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/writing_dialog"
    android:layout_width="match_parent"
    android:layout_height="400dp">

    <TextView
        android:id="@+id/textView8"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:fontFamily="@font/nexon"
        android:text="choose!"
        android:textAlignment="center"
        android:gravity="center"
        android:textColor="#341867"
        android:textSize="20dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/writing_dialog_ok"
        android:layout_width="65dp"
        android:layout_height="39dp"
        android:layout_marginEnd="20dp"
        android:background="#00FFFFFF"
        android:fontFamily="@font/nexon"
        android:text="ok"
        android:textColor="#341867"
        android:textSize="15dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline6" />

    <Button
        android:id="@+id/writing_dialog_cancel"
        android:layout_width="65dp"
        android:layout_height="39dp"
        android:layout_marginEnd="30dp"
        android:background="#00FFFFFF"
        android:text="cancel"
        android:textColor="#341867"
        android:textSize="15dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/writing_dialog_ok"
        app:layout_constraintTop_toTopOf="@+id/guideline6" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_begin="355dp" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/writing_dialog_recy"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="20dp"
        app:layout_constraintBottom_toTopOf="@+id/guideline6"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView8" />

</androidx.constraintlayout.widget.ConstraintLayout>

recyclerview 单元

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/dialog_container"
    android:layout_width="match_parent"
    android:layout_height="45dp">

    <RadioButton
        android:id="@+id/dialog_radio"
        android:layout_width="0dp"
        android:layout_height="45dp"
        android:fontFamily="@font/nexon"
        android:text="시리즈 1"
        android:textSize="18dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

回收者视图适配器

public class WritingNovelAdapter extends RecyclerView.Adapter<WritingNovelAdapter.Holder>{
    private Context context;
    private ArrayList<WritingNovel_data> dataList;

    public WritingNovelAdapter(Context context,ArrayList<WritingNovel_data> dataList){
        this.context = context;
        this.dataList = dataList;
    }

    public static class Holder extends RecyclerView.ViewHolder{

        protected ConstraintLayout dialog_container;
        protected RadioButton dialog_radio;

        public Holder(View view){
            super(view);
            this.dialog_container = view.findViewById(R.id.dialog_container);
            this.dialog_radio = view.findViewById(R.id.dialog_radio);
        }
    }

    @Override
    public WritingNovelAdapter.Holder onCreateViewHolder(ViewGroup parent,int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.writing_dialog_cell,parent,false);
        Holder holder = new WritingNovelAdapter.Holder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull WritingNovelAdapter.Holder holder,final int position) {

        String title = dataList.get(position).title;
        if(title.length() > 16){
            title = title.substring(0,15) + "…";
        }
        holder.dialog_radio.setText(title);

        holder.dialog_container.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                //????????????????????????????
            }
        });
    }

    @Override
    public int getItemCount() {
        if(dataList == null){
            return 0;
        }
        else{
            return dataList.size();
        }
    }

}

自定义对话框类

class CustomDialog {

    private Context context;

    public CustomDialog(Context context)
    {
        this.context = context;
    }

    public void callDialog()
    {
        final Dialog dialog = new Dialog(context);

        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.writing_novel_series_dialog);
        dialog.show();

        final RecyclerView writing_dialog_recy = dialog.findViewById(R.id.writing_dialog_recy);
        final Button writing_dialog_ok = dialog.findViewById(R.id.writing_dialog_ok);
        final Button writing_dialog_cancel = dialog.findViewById(R.id.writing_dialog_cancel);

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

            }
        });

        writing_dialog_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });


    }

}

====EDIT-1====

我在这里调用我的对话!

public class writing_novel extends AppCompatActivity {
    private static final int GALLERY_REQUEST = 979;
    private RichEditor mEditor;
    private ColorPicker colorPicker;
    androidx.appcompat.app.AlertDialog.Builder textSizeDialogBuilder;
    private NumberPicker textPicker;
    androidx.appcompat.app.AlertDialog.Builder youtubeDialogBuilder;
    private EditText etYoutubeUrl;
    private Button writing_novel_btn_series;
    private ImageButton writing_novel_novel_ibtn_next;



    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:{
                finish();
                return true;
            }
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_writing_novel);


        Toolbar toolbar = findViewById(R.id.writing_novel_main_toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);

        writing_novel_novel_ibtn_next = findViewById(R.id.writing_novel_novel_ibtn_next);

        writing_novel_novel_ibtn_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(writing_novel.this);

                builder.setTitle("정말 다음으로 넘어가시겠습니까?").setMessage("다음으로 넘어가기전,한번 더 검토해주세요.");

                builder.setPositiveButton("넘어가기",new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog,int id)
                    {
                        Toast.makeText(getApplicationContext(),"OK Click",Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(writing_novel.this,decide_novel_title.class);
                        
                        startActivity(intent);
                    }

                });

                builder.setNegativeButton("취소","Cancel Click",Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                    }
                });

                builder.setCancelable(false);
                builder.create().show();
            }
        });

        writing_novel_btn_series = findViewById(R.id.writing_novel_btn_series);

        writing_novel_btn_series.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                
                Bundle args = new Bundle();
                args.putString("id","");
                DialogFragment dialogFragment = new DialogFragment();
                dialogFragment.setArguments(args);
                dialogFragment.show(getFragmentManager(),"id");

                CustomDialog dialog = new CustomDialog(writing_novel.this);
                dialog.show(getSupportFragmentManager(),"CustomDialog");
            }
        });

解决方法

如果我理解正确的话,您正在尝试弄清楚如何显示 RecyclerView 项目列表,以及当单击某个项目时,在下面的 TextView 中显示其数据。如果我错了,请纠正我。

对于第一步,您已经接近了。您需要做的就是实例化一个新的布局管理器和一个适配器类的实例,并将它们传递给您的 RecyclerView。

将此添加到您的 CustomDialog 类:

public void callDialog() {
    ...

    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(context);
    writing_dialog_recy.setLayoutManager(layoutManager);

    // I'm assumming you are passing a list of data here
    WritingNovelAdapter adapter = new WritingNovelAdapter(context,dataList);
    writing_dialog_recy.setAdapter(adapter);

    ...

至于在 textView 中显示文本,您有几种不同的实现方式。如果没有看到其余的相关代码很难说,但我建议实现回调接口并从您的 ViewHolder 调用该方法,如下所示:

  1. 在 Adapter 类中定义接口
public interface CallbackInterface {
void showText(String text);
}
  1. 在您的 CustomDialog 类中实现回调接口并实现 setText 方法,您将在该方法中设置 TextView 中的文本。这将要求您有一个要在其中显示该文本的 TextView 实例,这意味着您必须在某处调用它:TextView textView = findViewById(R.id.textView8);
class CustomDialog implements CallbackInterface {
... 

    public void showText(String text) {
        textView.setText(text);
    }
}
  1. 将 CustomDialog 的实例传递给适配器(确保重新定义适配器构造函数以接受 CustomDialog 的实例
public void callDialog() {
    ...

    // I'm assumming you are passing a list of data here
    WritingNovelAdapter adapter = new WritingNovelAdapter(context,dataList,this);
    writing_dialog_recy.setAdapter(adapter);

    ...
}
  1. 点击recyclerview单元格时从适配器类调用回调方法
public class WritingNovelAdapter extends RecyclerView.Adapter<WritingNovelAdapter.Holder> {
    private Context context;
    private ArrayList<WritingNovel_data> dataList;
    private CallbackInterface callbackInterface;

    public WritingNovelAdapter(Context context,ArrayList<WritingNovel_data> 
    dataList,CallbackInterface callbackInterface){
        this.context = context;
        this.dataList = dataList;
        this.callbackInterface = callbackInterface;
    }

    ...

    holder.dialog_container.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                callbackInterface.showText(title);
            }
        });

}

编辑 #1

您的评论表明您的对话框没有显示。除非您在 CustomDialog 类中遗漏了一些代码,否则所有 CustomDialog 类都是一个 Java 类。您需要扩展一个超类,例如 AlertDialog 或 DialogFragment。我会尽力总结如何做到这一点,但你应该看看 android 文档 -> https://developer.android.com/guide/topics/ui/dialogs

以下是您可以尝试创建的 DialogFragment 示例:

public class CustomDialog extends DialogFragment implements CallbackInterface {

    private Context context;
    private TextView textView;
    private RecyclerView writing_dialog_recy;

    public CustomDialog(Context context) {
        this.context = context;
    }

    /* This is the method which builds and essentially shows the dialog */
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {

        AlertDialog.Builder builder = new AlertDialog.Builder(context);

        LayoutInflater inflater = getActivity().getLayoutInflater();

        // Inflate your view that contains the recyclerview
        View view = inflater.inflate(R.layout.custom_dialog);

        // Your text view where you want to show the text after an item is clicked
        textView = view.findViewById(R.id.textView8);

        // Your recyclerview in your custom_dialog.xml
        writing_dialog_recy = view.findViewById(R.id.writing_dialog_recy);

        // Create the layout manager
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(context);
        writing_dialog_recy.setLayoutManager(layoutManager);

        // Create and set the adapter
        WritingNovelAdapter adapter = new WritingNovelAdapter(context,this);
        writing_dialog_recy.setAdapter(adapter);

        builder.setView(view);

        builder.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog,int which) {
                        // do whatever you want when user clicks the positive button
                    }
                });
        builder.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog,int which) {
                dialog.dismiss();
            }
        });

        return builder.create(); // return the dialog builder

    }

    public void showText(String text) {
        textView.setText(text);
    }
}

然后在您创建此对话框的任何活动中,您都会显示 DialogFragment 并将其传递给活动的 FragmentManager 和一个标签

CustomDialog dialog = new CustomDialog(this);
dialog.show(getSupportFragmentManager(),"CustomDialog");

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res