繁体   English   中英

如何在 AlertDialog 中将 onClick 放在 CardView 上

[英]How to put an onClick on a CardView in an AlertDialog

我正在尝试在 AlertDialog 中执行 CardView 的 StartActivity 但它不起作用

我在互联网上找不到类似的东西,我也尝试了一个按钮,我得到了同样的错误(见帖子底部的 LogCat)

这是我的 AlertDialog 布局:

<androidx.cardview.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="15dp"
    android:layout_marginEnd="15dp"
    app:cardBackgroundColor="@color/main_color_bg"
    app:cardCornerRadius="4.5dp"
    app:cardElevation="12dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <androidx.cardview.widget.CardView
            android:id="@+id/settings_support_btn"
            android:layout_width="match_parent"
            android:layout_height="65dp"
            android:layout_marginStart="15dp"
            android:layout_marginEnd="15dp"
            android:layout_marginTop="15dp"
            app:cardBackgroundColor="@color/content_background"
            app:cardCornerRadius="4.5dp"
            app:cardElevation="12dp">
        </androidx.cardview.widget.CardView>
        
    </LinearLayout>

</androidx.cardview.widget.CardView>

这是我的主要

AlertDialog settingsDialog;

protected void onCreate(Bundle savedInstanceState) {
//Other code here...

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

  View view = getLayoutInflater().inflate(R.layout.settings_dialog, null);
        CardView settingsSupportBtn = (CardView) findViewById(R.id.settings_support_btn);
        settingsSupportBtn.setOnClickListener(view1 -> {
            startActivity(new Intent(Main.this, SettingsSupport.class));
            settingsDialog.dismiss();
        });

        builder.setView(view);
        settingsDialog = builder.create();

        clickEvent();
}

public void clickEvent() {
  settingsBtn.setOnClickListener(view -> {
        settingsDialog.show();
 });

}

这是我的 LogCat:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.package.test.android/com.package.test.android.Main}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.cardview.widget.CardView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
...
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.cardview.widget.CardView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

更改此行

CardView settingsSupportBtn = (CardView) findViewById(R.id.settings_support_btn);

CardView settingsSupportBtn = (CardView) view.findViewById(R.id.settings_support_btn);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM