【问题标题】:Unable to show AlertDialog in recycler view adapter class无法在回收器视图适配器类中显示 AlertDialog
【发布时间】:2019-12-25 16:56:03
【问题描述】:

我在回收站视图行中有按钮,我想在按钮单击时显示警报对话框。我在适配器类的onBindViewHolder 方法中设置onClickListener,但是当我单击按钮时,它显示下面给出的运行时错误:

> 2019-12-25 22:22:57.140 11041-11041/com.app.aamku E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.app.aamku, PID: 11041
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
    at android.view.ViewRootImpl.setView(ViewRootImpl.java:765)
    at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:356)
    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
    at android.app.Dialog.show(Dialog.java:330)
    at Adapters.ProductAdapter$2.onClick(ProductAdapter.java:174)
    at android.view.View.performClick(View.java:6294)
    at android.view.View$PerformClick.run(View.java:24770)
    at android.os.Handler.handleCallback(Handler.java:790)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6494)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

下面是我的代码:

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

private Context context;
private List<ProductsModel> productList;

public ProductAdapter(Context context, List<ProductsModel> productList) {
    this.context = context;
    this.productList = productList;
}

@NonNull
@Override
public ProductAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.selectpack_layout,parent,false);

    ViewHolder viewHolder = new ViewHolder(v);

    return viewHolder;
}

@Override
public void onBindViewHolder(@NonNull final ProductAdapter.ViewHolder holder, final int position) {

    final ProductsModel model = productList.get(position);

    holder.marketName.setText(model.getMarketName());

    holder.order.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setMessage("Confirm order");
            builder.setCancelable(true);
            builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                    dialogInterface.cancel();
                }
            });
            builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                   Toast.makeText(context,"Hello",Toast.Length_SHORT).show();

                }
            });

            AlertDialog alertDialog = builder.create();
            alertDialog.show();

        }
    });
}

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

public class ViewHolder extends RecyclerView.ViewHolder{

    Button order;
    TextView marketName;

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

        order = itemView.findViewById(R.id.order);
        marketName = itemView.findViewById(R.id.marketName);

     }
   }
}

我该如何克服这个问题,请让我知道我做错了什么,任何帮助将不胜感激。

谢谢

【问题讨论】:

标签: android


【解决方案1】:

我刚刚复制了您的对话框代码并创建了简单的演示,它对我来说运行良好。查看演示:

适配器代码:

import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;

public class MyListAdapter extends RecyclerView.Adapter<MyListAdapter.ViewHolder> {
private Context context;

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

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
    View listItem = layoutInflater.inflate(R.layout.list_item, parent, false);
    ViewHolder viewHolder = new ViewHolder(listItem);
    return viewHolder;
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    holder.textView.setText("Fake item list " + position);

    holder.textView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setMessage("Confirm order");
            builder.setCancelable(true);
            builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                    dialogInterface.cancel();
                }
            });
            builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    Toast.makeText(context, "Hello", Toast.LENGTH_SHORT).show();
                }
            });
            AlertDialog alertDialog = builder.create();
            alertDialog.show();
        }
    });

}


@Override
public int getItemCount() {
    return 15;
}

public static class ViewHolder extends RecyclerView.ViewHolder {
    public TextView textView;

    public ViewHolder(View itemView) {
        super(itemView);
        this.textView = (TextView) itemView.findViewById(R.id.textView);
     }
   }
   }

活动代码:

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    MyListAdapter adapter = new MyListAdapter(this);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setAdapter(adapter);
   }
  }

活动 xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView
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:scrollbars="vertical"
android:id="@+id/recyclerView"
tools:context=".MainActivity">
</androidx.recyclerview.widget.RecyclerView>

列表项 XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeightLarge"
>


<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:text="item"
    android:gravity="center_vertical"
    android:textSize="16sp"/>

 </LinearLayout>

还要查看导入,这里我使用的是 Android x 库。

【讨论】:

    【解决方案2】:

    将活动活动定义为变量 在构造函数中传递 YourActivity.this 并使用 AlertDialog.Builder builder = new AlertDialog.Builder(activity); 创建对话框

    【讨论】:

      【解决方案3】:

      当我想在片段上按下项目后添加 alertDialog 时遇到了相关问题。

      alertDialog 首先需要一个扩展活动的 java 类,所以我知道你有一个适配器,但你能把它翻过来吗?

      点击recyclerview中的列表后,这将使用扩展activity(具有onCreate方法)的类上的公共函数,该activity包含recyclerview中的列表并一路传递任何变量。

      功能是使用传递的变量运行alertDialog,我认为你应该没问题。

      或者您可以手动将上下文更改为您正在进行的活动,也许这有效。

      很抱歉我不能给你举个例子,因为我是afk rn。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-05
        • 1970-01-01
        • 2017-04-28
        • 2019-05-03
        • 2021-09-13
        相关资源
        最近更新 更多