onClickListener中的AlertDialog

时间:2012-01-11 02:50:27

标签: android alertdialog android-alertdialog

我正在尝试从onClickListener启动AlertDialog但是我收到以下错误。

The constructor AlertDialog.Builder(new View.OnClickListener(){}) is undefined  

有谁知道如何解决这个问题?

        mRecordButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            new AlertDialog.Builder( this )
            .setTitle( "Cast Recording" )
            .setMessage( "Now recording your message" )
            .setPositiveButton( "Save", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Log.d( "AlertDialog", "Positive" );
                }
            })
            .setNegativeButton( "Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Log.d( "AlertDialog", "Negative" );
                }
            } )
            .show();
        }
    });

3 个答案:

答案 0 :(得分:30)

更改此行

new AlertDialog.Builder( this );

new AlertDialog.Builder( YourActivity.this );

这是因为构造函数需要Context类型& OnclickListner is not a Context type所以你使用了Activity的对象。

我希望它有所帮助..

答案 1 :(得分:0)

new AlertDialog.Builder( this )中,this指的是侦听器,而不是外部类实例。

答案 2 :(得分:0)

步骤1。创建文件activity_main.xml

>>> for sent in tokenize_text:
...     for word in sent:
...         print(word)
...     break
... 

第2步。创建一个类MainActivity.java

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity"
    android:background="#d7ecd6"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is a TextView."
        android:textColor="#ff5ff4"
        />
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Apply Big Font Size"
        android:layout_below="@id/tv"
        />
</RelativeLayout>

在线代码: AlertDialog onlick in android