如何在android中创建自定义警报对话框?

时间:2013-09-18 08:12:24

标签: android alertdialog

我正在开发一个示例应用程序。我可以在按钮点击时显示警告,有点小按钮。但是现在我想显示一个弹出窗口,其中包含用户名(标签)和文本字段(编辑字段) 和一个按钮。 点击button.can我为它做了另一个弹出式xml文件?

public void selfDestruct(View view) {
         // Kabloey
         Log.d("Naveen", "Test====");
         System.out.println("----------------------ghfgjhf-----------------");
         AlertDialog alertDialog = new AlertDialog.Builder(SecondActivity.this).create();
         alertDialog.setTitle("Reset...");
         alertDialog.setMessage("R u sure?");
         alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int which) {

               //here you can add functions

            } });
         alertDialog.show();
     }

   <Button
     android:layout_height="wrap_content"
     android:layout_width="wrap_content"
     android:text="@string/self_destruct"
     android:onClick="selfDestruct" />

9 个答案:

答案 0 :(得分:30)

custom_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >


    <EditText
        android:id="@+id/editText"
        android:hint="Enter some thing"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

    <requestFocus />
    </EditText>

    <LinearLayout                
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"   
        android:layout_marginTop="10dp">     

        <Button
            android:id="@+id/save"
            android:layout_marginTop="15dp"
            android:layout_weight="1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="SAVE" />

        <Button
            android:id="@+id/cancel"
            android:layout_marginTop="15dp"
            android:layout_weight="1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Cancel" />

    </LinearLayout>
</LinearLayout>

需要对custom_dialog.xml进行充气

final Dialog dialog = new Dialog(this);

dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Custom Alert Dialog");

final EditText editText = (EditText) dialog.findViewById(R.id.editText);
Button btnSave          = (Button) dialog.findViewById(R.id.save);
Button btnCancel        = (Button) dialog.findViewById(R.id.cancel);
dialog.show();

答案 1 :(得分:4)

您可以进行常规活动并将android:theme设置为对话框:

   <activity
        android:name="com.example.carsharingkitdemo.YourPopUpActivity"
        android:theme="@android:style/Theme.Holo.Dialog" >
    </activity>

并在此活动的xml文件中,您可以决定此对话框字段的高度和宽度。例如:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="300dp"
android:layout_height="100dp">

重要的是清单部分。

答案 2 :(得分:3)

答案 3 :(得分:2)

您可以使用对话,如下代码:

final Dialog dialog = new Dialog(context);
// dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom);
dialog.setTitle("Title...");

// set the custom dialog components - text, image and button
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Android custom dialog example!");
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();

如果您要删除标题栏,请在定义后使用此代码:

dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

答案 4 :(得分:1)

试试这个......

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Reset...").setView(editText)
   .setMessage("R u sure?").setCancelable(true)
   .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int arg1) {
        //Do here whatever.....
    }
});
AlertDialog alert = builder.create();
alert.show();
}

答案 5 :(得分:1)

以下是xml代码和活动代码。

 <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="56dp"
        android:text="Popup Window will display on this Activity" />

    <Button
        android:id="@+id/popupbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Show Popup" />

</RelativeLayout>

活动文件

package com.nkm.popup;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

public class PopupDemoActivity extends Activity implements OnClickListener {
LinearLayout layoutOfPopup;
PopupWindow popupMessage;
Button popupButton, insidePopupButton;
TextView popupText;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    init();
    popupInit();
}

public void init() {
    popupButton = (Button) findViewById(R.id.popupbutton);
    popupText = new TextView(this);
    insidePopupButton = new Button(this);
    layoutOfPopup = new LinearLayout(this);
    insidePopupButton.setText("OK");
    popupText.setText("This is Popup Window.press OK to dismiss         it.");
    popupText.setPadding(0, 0, 0, 20);
    layoutOfPopup.setOrientation(1);
    layoutOfPopup.addView(popupText);
    layoutOfPopup.addView(insidePopupButton);
}

public void popupInit() {
    popupButton.setOnClickListener(this);
    insidePopupButton.setOnClickListener(this);
    popupMessage = new PopupWindow(layoutOfPopup, LayoutParams.FILL_PARENT,
            LayoutParams.WRAP_CONTENT);
    popupMessage.setContentView(layoutOfPopup);
}

@Override
public void onClick(View v) {

    if (v.getId() == R.id.popupbutton) {
        popupMessage.showAsDropDown(popupButton, 0, 0);
    }

    else {
        popupMessage.dismiss();
    }
  }
}

答案 6 :(得分:1)

它为我工作

Dialog m_dialog; 
m_dialog = new Dialog(BusinessDetail.this);
            m_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

            LayoutInflater m_inflater = LayoutInflater.from(BusinessDetail.this);
            View m_view = m_inflater.inflate(R.layout.rateus_popup, null);
            myPopLay = (LinearLayout) m_view.findViewById(R.id.myPopLay);
m_dialog.setContentView(m_view);
            m_dialog.show();

答案 7 :(得分:0)

使用以下编码在android中显示弹出窗口。

AlertDialog.builder builder=new AlertDilaog.Builder(this);
    builder.setMessage("PopUP Example");
    AlertDialog alert=builder.create();
    alert.setTitle("");
    alert.show();

    new Handler.postDelayed(new Runnable()
    {
    @override
    public void run()
    {
  //TODO
    alert.dismiss();
    }
    },1*1000);
    }

Youtube链接:https://www.youtube.com/watch?v=SEsVTTl6exg

答案 8 :(得分:0)

我们将使用PopupWindow类来创建弹出窗口。

我想提到的一件事是我们希望弹出窗口附加到打开它的按钮上。例如,如果上面屏幕截图中的“显示弹出窗口”按钮位于屏幕中间,我们希望弹出窗口保持按钮的位置。要实现这一点,首先我们应该在屏幕上获得按钮的“x”和“y”位置,并将它们传递给弹出窗口。然后我们将使用偏移来正确对齐弹出窗口 - 向右移动一点,然后向下移动一点,这样它就不会与整个按钮重叠。

另一个想法我想提一下,我们将使用9补丁背景图片作为弹出窗口,因此它看起来会更加花哨。但是当然你可以跳过它并放置你想要的任何背景,或者根本没有背景。

创建layout / main.xml文件并添加一个按钮:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#CCC"
android:orientation="vertical" >

<Button
   android:id="@+id/show_popup"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Show Popup" />

</LinearLayout>

创建一个新的布局文件:layout / popup_layout.xml,用于定义弹出窗口的布局。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="wrap_content"
   android:id="@+id/popup"
   android:layout_height="wrap_content"
   android:background="@drawable/popup_bg"
   android:orientation="vertical" >

<TextView
   android:id="@+id/textView1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Popup"
   android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
   android:id="@+id/textView2"
   android:layout_marginTop="5dp"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="This is a simple popup" />

<Button
   android:id="@+id/close"
   android:layout_marginTop="10dp"
   android:layout_gravity="center_horizontal"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Close" />

</LinearLayout>

现在是最有趣的部分。打开TestPopupActivity并使用下面的代码填充它。仔细阅读评论以了解正在发生的事情。

 public class TestPopupActivity extends Activity {

//The "x" and "y" position of the "Show Button" on screen.
Point p;

@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);

   Button btn_show = (Button) findViewById(R.id.show_popup);
   btn_show.setOnClickListener(new OnClickListener() {
     @Override
     public void onClick(View arg0) {

       //Open popup window
       if (p != null)
       showPopup(TestPopupActivity.this, p);
     }
   });
}

// Get the x and y position after the button is draw on screen
// (It's important to note that we can't get the position in the onCreate(),
// because at that stage most probably the view isn't drawn yet, so it will return (0, 0))
@Override
public void onWindowFocusChanged(boolean hasFocus) {

   int[] location = new int[2];
   Button button = (Button) findViewById(R.id.show_popup);

   // Get the x, y location and store it in the location[] array
   // location[0] = x, location[1] = y.
   button.getLocationOnScreen(location);

   //Initialize the Point with x, and y positions
   p = new Point();
   p.x = location[0];
   p.y = location[1];
}

// The method that displays the popup.
private void showPopup(final Activity context, Point p) {
   int popupWidth = 200;
   int popupHeight = 150;

   // Inflate the popup_layout.xml
   LinearLayout viewGroup = (LinearLayout) context.findViewById(R.id.popup);
   LayoutInflater layoutInflater = (LayoutInflater) context
     .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   View layout = layoutInflater.inflate(R.layout.popup_layout, viewGroup);

   // Creating the PopupWindow
   final PopupWindow popup = new PopupWindow(context);
   popup.setContentView(layout);
   popup.setWidth(popupWidth);
   popup.setHeight(popupHeight);
   popup.setFocusable(true);

   // Some offset to align the popup a bit to the right, and a bit down, relative to button's position.
   int OFFSET_X = 30;
   int OFFSET_Y = 30;

   // Clear the default translucent background
   popup.setBackgroundDrawable(new BitmapDrawable());

   // Displaying the popup at the specified location, + offsets.
   popup.showAtLocation(layout, Gravity.NO_GRAVITY, p.x + OFFSET_X, p.y + OFFSET_Y);

   // Getting a reference to Close button, and close the popup when clicked.
   Button close = (Button) layout.findViewById(R.id.close);
   close.setOnClickListener(new OnClickListener() {

     @Override
     public void onClick(View v) {
       popup.dismiss();
     }
   });
}
}