不显示警报对话框

发布于 2024-12-12 10:17:22 字数 582 浏览 0 评论 0原文

大家好,我正在通过单击按钮在 android 中创建一个警报对话框。我使用了 XML 的 onClick 属性和调用函数。我的代码是

public void selectPhoneType(View view)
{
    String [] item = {"Home", "Work", "Mobile", "Work Fax", "Home Fax", "Pager", "Other", "Custom"};
    AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
    builder.setTitle("Select Label");
    AlertDialog alert = builder.create();
    alert.show();}

,但此代码没有显示警报并给出错误,例如

BadTokenException: Unable to add window -- token null is not for an application. 

请告诉我此代码有什么问题。

Hi all I am creating an alert dialog in android by clicking a button. I used onClick property of XML and calling function. My code is

public void selectPhoneType(View view)
{
    String [] item = {"Home", "Work", "Mobile", "Work Fax", "Home Fax", "Pager", "Other", "Custom"};
    AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
    builder.setTitle("Select Label");
    AlertDialog alert = builder.create();
    alert.show();}

but this code is not showing alert and giving error like

BadTokenException: Unable to add window -- token null is not for an application. 

Please tell me what is wrong with this code.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

无言温柔 2024-12-19 10:17:22
new AlertDialog.Builder(getApplicationContext());

我认为这就是问题所在。你有没有尝试过:

new AlertDialog.Builder(YourActivityClassName.this);
new AlertDialog.Builder(getApplicationContext());

I think this is the problem. Have you tried:

new AlertDialog.Builder(YourActivityClassName.this);
夜巴黎 2024-12-19 10:17:22

传递 requireActivity() 而不是 requireContext() 对我有用..!!
我认为这需要活动背景!

Passing requireActivity() instead of requireContext() worked for me..!!
I think it requires activity context!!.

挽清梦 2024-12-19 10:17:22

如果您在后台线程中调用对话框代码,那么它将无法工作。
你应该在主线程中调用UI相关的代码,如果你不这样做,那么它不会向你显示对话框。

  1. 如果您想在后台任务中显示对话框,请改用处理程序。

    new Handler().post(new Runnable(){
    显示对话框();
    })

  2. 确保调用了 create()show() 方法。

  3. 永远不要忘记第一点和第二点。

If you are calling dialog code in background thread then it won't work.
You should call UI related code in main thread, if you are not doing it then it will not show you the dialog.

  1. If you want show the dialog in the background task then use handler instead.

    new Handler().post(new Runnable(){
    showDialog();
    })

  2. Make sure create() and show() method is called.

  3. Never forgot 1st and 2nd point.

落叶缤纷 2024-12-19 10:17:22

就我而言,用 android.app.AlertDialog 替换 androidx.appcompat.app.AlertDialog 帮助了我:

val builder = android.app.AlertDialog.Builder(requireActivity())

In my case, replacing androidx.appcompat.app.AlertDialog by android.app.AlertDialog helped me:

val builder = android.app.AlertDialog.Builder(requireActivity())
时光无声 2024-12-19 10:17:22

Activity_main.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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageButton
        android:id="@+id/grocery"
        android:layout_width="65dp"
        android:layout_height="72dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.089"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.024"
        tools:srcCompat="@tools:sample/avatars" />

    <TextView
        android:id="@+id/chips"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="192dp"
        android:text="chips"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.167"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/fruits"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="120dp"
        android:text="fruits"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.166"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/fruit_input"
        android:layout_width="166dp"
        android:layout_height="48dp"
        android:layout_marginTop="120dp"
        android:ems="10"
        android:inputType="text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.559"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/chips_input"
        android:layout_width="202dp"
        android:layout_height="49dp"
        android:layout_marginTop="180dp"
        android:ems="10"
        android:inputType="text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.58"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ListView
        android:id="@+id/list"
        android:layout_width="171dp"
        android:layout_height="291dp"
        android:layout_marginTop="232dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.175"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/submit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="108dp"
        android:text="submit"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.344"
        app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt-

package com.example.practice

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.EditText
import android.widget.ImageButton
import android.widget.ListView
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import java.lang.Exception

class MainActivity : AppCompatActivity() {
    private var total=0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val fruits:TextView=findViewById(R.id.fruits)
        val chips:TextView=findViewById(R.id.chips)
        val chips_input:EditText=findViewById(R.id.chips_input)
        val fruits_input:EditText=findViewById(R.id.fruit_input)
        val grocery:ImageButton=findViewById(R.id.grocery)
        val listView:ListView=findViewById(R.id.list)
        val submit:Button=findViewById(R.id.submit)


        fruits.visibility=TextView.INVISIBLE
        chips.visibility=TextView.INVISIBLE
        fruits_input.visibility=TextView.INVISIBLE
        chips_input.visibility=TextView.INVISIBLE
        listView.visibility=TextView.INVISIBLE

           grocery.setOnClickListener {
               fruits.visibility = TextView.VISIBLE
               chips.visibility = TextView.VISIBLE
               fruits_input.visibility = TextView.VISIBLE
               chips_input.visibility = TextView.VISIBLE
               listView.visibility = TextView.VISIBLE
                try{
               var fruit_in = fruits_input.text.toString()
               var chips_in = chips_input.text.toString()

               var fruit_qty = fruit_in.toInt()
               var chips_qty = chips_in.toInt()


               var fruit_price = 100
               var chips_price = 200

               var fruits_tot = fruit_price * fruit_qty
               var chips_tot = chips_qty * chips_price

               total = fruits_tot + chips_tot

               val values = arrayOf("Fruits Total $fruits_tot", "Chips Total $chips_tot")
               val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, values)
               listView.adapter = adapter
           }
        catch(e:Exception) {

        }
           }
           submit.setOnClickListener {
               val builder=AlertDialog.Builder(this)
               builder.setTitle("Confirm")
               builder.setMessage("Total is $total")
               builder.setCancelable(false)
               builder.setPositiveButton("Yes"){_,_ ->
                   var ftotal=total.toDouble()
                   if(total>5000){
                       ftotal=total*0.9
                   }
                   val intent= Intent(this,Display::class.java).apply{
                       putExtra("total",ftotal)
                   }
                   startActivity(intent)
               }
               builder.setNegativeButton("NO"){dialog,_ ->
                   dialog.cancel()
               }
               val alertDialog=builder.create()
               alertDialog.show()
           }


    }
}

Activity_display.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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Display">

    <TextView
        android:id="@+id/balance"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="112dp"
        android:text="Balance"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.254"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/value"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="112dp"
        android:text="10000"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.595"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/buy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="320dp"
        android:text="Buy"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.411"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Display.kt-

package com.example.practice

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast


class Display : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_display)
        val buy:Button=findViewById(R.id.buy)
        val value:TextView=findViewById(R.id.value)
        buy.setOnClickListener {
            try{
                val total=intent.getDoubleExtra("total",0.0)
                val bal=value.text.toString().toDouble()
                val final=bal-total
                value.text=final.toString()
                Toast.makeText(this,"Balance is $final",Toast.LENGTH_SHORT).show()
            }
            catch (e:Exception){

            }
        }
    }
}

activity_main.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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageButton
        android:id="@+id/grocery"
        android:layout_width="65dp"
        android:layout_height="72dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.089"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.024"
        tools:srcCompat="@tools:sample/avatars" />

    <TextView
        android:id="@+id/chips"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="192dp"
        android:text="chips"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.167"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/fruits"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="120dp"
        android:text="fruits"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.166"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/fruit_input"
        android:layout_width="166dp"
        android:layout_height="48dp"
        android:layout_marginTop="120dp"
        android:ems="10"
        android:inputType="text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.559"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/chips_input"
        android:layout_width="202dp"
        android:layout_height="49dp"
        android:layout_marginTop="180dp"
        android:ems="10"
        android:inputType="text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.58"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ListView
        android:id="@+id/list"
        android:layout_width="171dp"
        android:layout_height="291dp"
        android:layout_marginTop="232dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.175"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/submit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="108dp"
        android:text="submit"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.344"
        app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt-

package com.example.practice

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.EditText
import android.widget.ImageButton
import android.widget.ListView
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import java.lang.Exception

class MainActivity : AppCompatActivity() {
    private var total=0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val fruits:TextView=findViewById(R.id.fruits)
        val chips:TextView=findViewById(R.id.chips)
        val chips_input:EditText=findViewById(R.id.chips_input)
        val fruits_input:EditText=findViewById(R.id.fruit_input)
        val grocery:ImageButton=findViewById(R.id.grocery)
        val listView:ListView=findViewById(R.id.list)
        val submit:Button=findViewById(R.id.submit)


        fruits.visibility=TextView.INVISIBLE
        chips.visibility=TextView.INVISIBLE
        fruits_input.visibility=TextView.INVISIBLE
        chips_input.visibility=TextView.INVISIBLE
        listView.visibility=TextView.INVISIBLE

           grocery.setOnClickListener {
               fruits.visibility = TextView.VISIBLE
               chips.visibility = TextView.VISIBLE
               fruits_input.visibility = TextView.VISIBLE
               chips_input.visibility = TextView.VISIBLE
               listView.visibility = TextView.VISIBLE
                try{
               var fruit_in = fruits_input.text.toString()
               var chips_in = chips_input.text.toString()

               var fruit_qty = fruit_in.toInt()
               var chips_qty = chips_in.toInt()


               var fruit_price = 100
               var chips_price = 200

               var fruits_tot = fruit_price * fruit_qty
               var chips_tot = chips_qty * chips_price

               total = fruits_tot + chips_tot

               val values = arrayOf("Fruits Total $fruits_tot", "Chips Total $chips_tot")
               val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, values)
               listView.adapter = adapter
           }
        catch(e:Exception) {

        }
           }
           submit.setOnClickListener {
               val builder=AlertDialog.Builder(this)
               builder.setTitle("Confirm")
               builder.setMessage("Total is $total")
               builder.setCancelable(false)
               builder.setPositiveButton("Yes"){_,_ ->
                   var ftotal=total.toDouble()
                   if(total>5000){
                       ftotal=total*0.9
                   }
                   val intent= Intent(this,Display::class.java).apply{
                       putExtra("total",ftotal)
                   }
                   startActivity(intent)
               }
               builder.setNegativeButton("NO"){dialog,_ ->
                   dialog.cancel()
               }
               val alertDialog=builder.create()
               alertDialog.show()
           }


    }
}

activity_display.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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Display">

    <TextView
        android:id="@+id/balance"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="112dp"
        android:text="Balance"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.254"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/value"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="112dp"
        android:text="10000"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.595"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/buy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="320dp"
        android:text="Buy"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.411"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Display.kt-

package com.example.practice

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast


class Display : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_display)
        val buy:Button=findViewById(R.id.buy)
        val value:TextView=findViewById(R.id.value)
        buy.setOnClickListener {
            try{
                val total=intent.getDoubleExtra("total",0.0)
                val bal=value.text.toString().toDouble()
                val final=bal-total
                value.text=final.toString()
                Toast.makeText(this,"Balance is $final",Toast.LENGTH_SHORT).show()
            }
            catch (e:Exception){

            }
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文