android 无法在回收器视图适配器类中显示AlertDialog

b1payxdu  于 12个月前  发布在  Android
关注(0)|答案(4)|浏览(206)

我在回收器视图行中有按钮,我想在按钮单击时显示警报对话框。我在适配器类的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);

     }
   }
}


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

谢谢

72qzrwbm

72qzrwbm1#

我刚刚复制了你的对话框代码,并创建了简单的演示,它的工作对我来说很好。看看演示:
适配器代码:

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库。

x6yk4ghg

x6yk4ghg2#

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

kiayqfof

kiayqfof3#

我有相关的问题,当我想添加alertDialog后,按下片段上的项目。
alertDialog首先需要一个扩展Activity的Java类,所以我知道你有一个适配器,但你能把它翻过来吗?
在你点击列表视图中的列表后,这将调用类上的公共函数,扩展活动(有onCreate方法),它包含列表视图中的列表,并传递任何变量沿着。
函数是用传递的变量运行alertDialog,我认为这样应该没问题。
或者你可以手动改变你正在进行的活动的上下文,也许这是有效的。
很抱歉我不能给你给予一个例子,因为我很害怕。

dphi5xsq

dphi5xsq4#

总是回收器视图适配器有构造函数传递上下文不要传递这个getApplicationContext();
相反,键入当前上下文即示例。this

相关问题