Dialog中文文档

Dialog原英文版文档查看
部分尚未翻译……恳请各位大佬给予建议和指导,O(∩_∩)O~

继承关系

public class Dialog
extends Object implements DialogInterface, Window.Callback, KeyEvent.Callback, View.OnCreateContextMenuListener 
  • java.lang.Object
    • ↳ android.app.Dialog

已知的直接子类

类名介绍
AlertDialog一个可以展示1~3个按钮的Dialog。
AppCompatDialog基于AppCompat主题的Dialog。
CharacterPickerDialogDialog for choosing accented characters related to a base character.
PresentationBase class for presentations.

已知的非直接子类

类名介绍
AlertDialog一个可以展示1~3个按钮的子类Dialog。
BottomSheetDialogBase class for Dialogs styled as a bottom sheet.
DatePickerDialogA simple dialog containing an DatePicker.
MediaRouteChooserDialogThis class implements the route chooser dialog for MediaRouter.
MediaRouteControllerDialogThis class implements the route controller dialog for MediaRouter.
ProgressDialogThis class was deprecated in API level 26. ProgressDialog is a modal dialog, which prevents the user from interacting with the app. Instead of using this class, you should use a progress indicator like ProgressBar, which can be embedded in your app’s UI. Alternatively, you can use a notification to inform the user of the task’s progress.
TimePickerDialogA dialog that prompts the user for the time of day using a TimePicker.

  这是Dialog系列中的基类。
  注意:在Activity中提供了管理Dialog的创建、保存、恢复的功能。详情请见onCreateDialog(int)onPrepareDialog(int, Dialog)showDialog(int)以及dismissDialog(int)。如果你使用了这些方法,你可以使用getOwnerActivity()这个方法来获取管理这个Dialog的Activity。
  大多数时候,你都会希望有一个Dialog可以显示在你的输入法的顶部,因为如果文本输入是在输入法下部的话,输入文本也是挺尴尬的(其实TextView什么的也可以作为文本输入的载体)。你可以使用WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM来设置窗口的标志位(指定你的Dialog获取焦点或者默认不变),比如下面的示例代码:

getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

概要

继承的变量

  从android.content.DialogInterface这个接口继承而来。
  

类型说明
intBUTTON1
这个常量在API3的时候就被弃用了。 请使用BUTTON_POSITIVE
intBUTTON2
这个常量在API3的时候就被弃用了。 请使用BUTTON_NEGATIVE
intBUTTON3
这个常量在API3的时候就被弃用了。 请使用BUTTON_NEUTRAL
intBUTTON_NEGATIVE
Negative button的标识符。(一般是取消按钮)
intBUTTON_NEUTRAL
Neutral button的标识符。(一般是说明什么的按钮)
intBUTTON_POSITIVE
Positive button的标识符。(一般是确认按钮)

公有构造方法

类型说明
Dialog(Context context)使用默认的主题创建一个Dialog实例。
Dialog(Context context, int themeResId)使用自定义的主题来创建一个Dialog实例。

保护构造方法

类型
Dialog(Context context, boolean cancelable, DialogInterface.OnCancelListener cancelListener)

公有方法

类型函数名说明
voidaddContentView(View view, ViewGroup.LayoutParams params)添加一个附加的包含内容的View到屏幕。
voidcancel()取消Dialog。这个方法和dismiss()类似,但是它会调用你的DialogInterface.OnCancelListener方法(如果注册(registered)了的话)。从源码上看是,先调用了DialogInterface.OnCancelListener方法之后调用了dismiss()方法。
voidcloseOptionsMenu()以编程的方式关闭选项菜单。假如选项菜单已经关闭了的话,就不执行任何操作。
voidcreate()强制性立即创建对话框Dialog。
voiddismiss()关闭此对话框,将其从屏幕中删除。该方法是线程安全的。
booleandispatchGenericMotionEvent(MotionEvent ev)当有通用动作事件(generic motion events)执行的的时候触发该方法。
booleandispatchKeyEvent(KeyEvent event)触发该方法去处理关键的事件。
如果处理了的话就返回true。
其中KeyEvent永不为null。
booleandispatchKeyShortcutEvent(KeyEvent event)当有快捷按键事件产生的时候触发该方法。
如果处理了的话就返回true。
其中KeyEvent永不为null。
booleandispatchPopulateAccessibilityEvent(AccessibilityEvent event)触发该方法去分发处理AccessibilityEvents事件。
如果处理了的话就返回true。
其中KeyEvent永不为null。
booleandispatchTouchEvent(MotionEvent ev)触发该方法去分发处理触屏事件。
booleandispatchTrackballEvent(MotionEvent ev)当有轨迹球事件产生的时候触发该方法。
TfindViewById(int id)找到具有给定ID的第一个后代视图,如果ID无效(< 0),或者层次结构中没有匹配的视图,或者是对话框尚未完全创建(例如,通过show()或create )),这些都返回null。
ActionBargetActionBar()如果ActionBar存在的话,就返回附加到Dialog上的ActionBar。
final ContextgetContext()返回Dialog运行所在的Context。
ViewgetCurrentFocus()如果需要此Activity返回当前聚焦的视图,请在窗口上调用getCurrentFocus()。
LayoutInflatergetLayoutInflater()获取LayoutInflater对象。
这个值始终不为null。
主要用于动态载入View。
final ActivitygetOwnerActivity()返回管理这个Dialog的Activity。
final SearchEventgetSearchEvent()During the onSearchRequested() callbacks, this function will return the SearchEvent that triggered the callback, if it exists.
final intgetVolumeControlStream()
WindowgetWindow()返回当前Activity中的窗口(Window)视图。
voidhide()隐藏Dialog,但是并没有关闭(dismiss)Dialog。
voidinvalidateOptionsMenu()
booleanisShowing()当前的Dialog的是否显示,如果显示的话就返回true,如果没有显示的话就返回false。
voidonActionModeFinished(ActionMode mode)Called when an action mode has been finished. Note that if you override this method you should always call through to the superclass implementation by calling super.onActionModeFinished(mode).
voidonActionModeStarted(ActionMode mode)Called when an action mode has been started. Note that if you override this method you should always call through to the superclass implementation by calling super.onActionModeStarted(mode).
voidonAttachedToWindow()当窗口附加到窗口管理器时调用。
voidonBackPressed()当用户点击返回键的时候触发该方法。
voidonContentChanged()当屏幕中的内容发生改变时将会触发该方法。 (由于调用了Window.setContentView或者是Window.addContentView)。
booleanonContextItemSelected(MenuItem item)
voidonContextMenuClosed(Menu menu)
voidonCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)Called when the context menu for this view is being built.
booleanonCreateOptionsMenu(Menu menu)It is usually safe to proxy this call to the owner activity’s onCreateOptionsMenu(Menu) if the client desires the same menu for this Dialog.
booleanonCreatePanelMenu(int featureId, Menu menu)Initialize the contents of the menu for panel ‘featureId’.
ViewonCreatePanelView(int featureId)Instantiate the view to display in the panel for ‘featureId’.
voidonDetachedFromWindow()Called when the window has been attached to the window manager.
booleanonGenericMotionEvent(MotionEvent event)当通用事件(包括鼠标滚轮事件)没有被Dialog中任何一个View处理的话,就触发该方法。
booleanonKeyDown(int keyCode, KeyEvent event)当按下键的时候被触发。
booleanonKeyLongPress(int keyCode, KeyEvent event)默认实现是用KeyEvent.Callback.onKeyLongPress(): 始终返回fasle (不处理任何事件)。
booleanonKeyMultiple(int keyCode, int repeatCount, KeyEvent event)默认实现是用KeyEvent.Callback.onKeyMultiple(): 始终返回fasle (不处理任何事件)。
booleanonKeyShortcut(int keyCode, KeyEvent event)当Dialog中没有一个View处理快捷键点击事件的时候将会触发该方法。
booleanonKeyUp(int keyCode, KeyEvent event)当一个按键释放的时候触发该方法。
booleanonMenuItemSelected(int featureId, MenuItem item)Called when a panel’s menu item has been selected by the user.
booleanonMenuOpened(int featureId, Menu menu)Called when a panel’s menu is opened by the user.
booleanonOptionsItemSelected(MenuItem item)
voidonOptionsMenuClosed(Menu menu)
voidonPanelClosed(int featureId, Menu menu)Called when a panel is being closed.
booleanonPrepareOptionsMenu(Menu menu)It is usually safe to proxy this call to the owner activity’s onPrepareOptionsMenu(Menu) if the client desires the same menu for this Dialog.
booleanonPreparePanel(int featureId, View view, Menu menu)Prepare a panel to be displayed.
voidonRestoreInstanceState(Bundle savedInstanceState)Restore the state of the dialog from a previously saved bundle.
Bundle onSaveInstanceState()保存Dialog的状态到bundle中。
booleanonSearchRequested(SearchEvent searchEvent)This hook is called when the user signals the desire to start a search.
booleanonSearchRequested()This hook is called when the user signals the desire to start a search.
booleanonTouchEvent(MotionEvent event)当Dialog中没有任何一个View处理触屏事件的时候将会触发该方法。
booleanonTrackballEvent(MotionEvent event)当当前Activity中任何一个View都不处理轨迹球移动事件的时候将会触发该方法。
voidonWindowAttributesChanged(WindowManager.LayoutParams params)当当前窗口的属性改变的时候将会触发该方法。
voidonWindowFocusChanged(boolean hasFocus)当Window窗口的焦点改变的时候,这个hook将会触发该方法。
ActionModeonWindowStartingActionMode(ActionMode.Callback callback)当Window中的一个action模式被启用的时候这个方法将会触发该方法。
ActionModeonWindowStartingActionMode(ActionMode.Callback callback, int type)当Window中的一个action模式被启用的时候这个方法将会触发该方法。
voidopenContextMenu(View view)
voidopenOptionsMenu()
voidregisterForContextMenu(View view)
final booleanrequestWindowFeature(int featureId)启用(Enable)继承窗口属性。
voidsetCancelMessage(Message msg)设置一个message,在Dialog被cancel()的时候发出去。
voidsetCancelable(boolean flag)设置这个Dialog是否可以通过BACK键取消。
voidsetCanceledOnTouchOutside(boolean cancel)设置当触摸窗口边界之外是否可以取消此对话框。如果设置为true的话,就表示可通过点击外部来取消Dialog,反之,不可通过点击外部来取消Dialog。
voidsetContentView(int layoutResID)引入layout resource来设置屏幕的内容。
voidsetContentView(View view, ViewGroup.LayoutParams params)将屏幕内容设置为显式视图。
voidsetContentView(View view)将屏幕内容设置为显式视图。
voidsetDismissMessage(Message msg)设置一个message,当Dialog被dismiss()的时候发送出去。
final voidsetFeatureDrawable(int featureId, Drawable drawable)方便调用setFeatureDrawable(int,Drawable)。
final voidsetFeatureDrawableAlpha(int featureId, int alpha)方便调用setFeatureDrawableAlpha(int, int)。
final voidsetFeatureDrawableResource(int featureId, int resId)方便调用setFeatureDrawableResource(int, int)。
final voidsetFeatureDrawableUri(int featureId, Uri uri)方便调用setFeatureDrawableUri(int, Uri)。
voidsetOnCancelListener(DialogInterface.OnCancelListener listener)设置在取消对话框时调用的事件监听。
voidsetOnDismissListener(DialogInterface.OnDismissListener listener)设置在关闭对话框时调用的事件监听。
voidsetOnKeyListener(DialogInterface.OnKeyListener onKeyListener)设置如果将一个按键事件分发到Dialog中的回调事件。
voidsetOnShowListener(DialogInterface.OnShowListener listener)设置一个事件监听,当Dialog显示的时候触发该方法。
final voidsetOwnerActivity(Activity activity)设置当前Dialog的归哪一个Activity管理。
voidsetTitle(CharSequence title)设置Dialog窗口的标题。
voidsetTitle(int titleId)设置Dialog窗口的标题。
final voidsetVolumeControlStream(int streamType)默认情况下,这将使用所有者Activity的建议的流类型。
voidshow()启动Dialog并在屏幕上显示。
voidtakeKeyEvents(boolean get)请求按键事件来到此Dialog。
voidunregisterForContextMenu(View view)

其他

onGenericMotionEvent简要介绍

jiese1990的专栏 - android 处理鼠标滚轮事件

  Android处理鼠标滚轮事件,并不是如下函数:

  1. public boolean onKeyDown(int keyCode, KeyEvent event)
  2. public boolean dispatchKeyEvent(KeyEvent event)
  3. public boolean onTouchEvent(MotionEvent event)

  而是如下函数:

public boolean onGenericMotionEvent(MotionEvent event);

  所有View和Activity都可重写该函数,来自己处理滚轮事件,

/** 
* Implement this method to handle generic motion events. 
* 实现该方法来处理一般的MotionEvent; 
* 一般的motion events 描述,操纵杆的动作,鼠标honver、滚轮等 
*  
* @param event The generic motion event being processed. 
* @return True if the event was handled, false otherwise. 
*/  

@Override  
public boolean onGenericMotionEvent(MotionEvent event) {  
    //The input source is a pointing device associated with a display.  
    //输入源为可显示的指针设备,如:mouse pointing device(鼠标指针),stylus pointing device(尖笔设备)  
    if (0 != (event.getSource() & InputDevice.SOURCE_CLASS_POINTER)) {    
        switch (event.getAction()) {  
            // process the scroll wheel movement...处理滚轮事件  
            case MotionEvent.ACTION_SCROLL:   
            //获得垂直坐标上的滚动方向,也就是滚轮向下滚  
            if( event.getAxisValue(MotionEvent.AXIS_VSCROLL) < 0.0f){      
                Log.i("fortest::onGenericMotionEvent", "down" );  
            }  
            //获得垂直坐标上的滚动方向,也就是滚轮向上滚  
            else{  
                Log.i("fortest::onGenericMotionEvent", "up" );  
            }  
            return true;  
        }  
    }  
    return super.onGenericMotionEvent(event);  
}  

自定义Dialog实现点击外部事件处理

public interface BaseDialogListener {
    void outSideEvent();
}
public class BaseDialog extends AlertDialog {

    private BaseDialogListener baseDialogListener;

    public BaseDialog(@NonNull Context context) {
        super(context);
    }

    public BaseDialog(@NonNull Context context, @StyleRes int themeResId) {
        super(context, themeResId);
    }

    protected BaseDialog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
    }

    public void setBaseDialogListener(BaseDialogListener baseDialogListener) {
        this.baseDialogListener = baseDialogListener;
    }

    private void onTouchOutside(MotionEvent event) {
        if (this.baseDialogListener != null) {
            this.baseDialogListener.outSideEvent();
        }
    }

    @Override
    public boolean onTouchEvent(@NonNull MotionEvent event) {
        /* 触摸外部弹窗 */
        if (isOutOfBounds(getContext(), event)) {
            onTouchOutside(event);
        }
        return super.onTouchEvent(event);
    }

    private boolean isOutOfBounds(Context context, MotionEvent event) {
        final int x = (int) event.getX();
        final int y = (int) event.getY();
        final int slop = ViewConfiguration.get(context).getScaledWindowTouchSlop();
        if (getWindow() == null) {
            return false;
        }
        final View decorView = getWindow().getDecorView();
        return (x < -slop) || (y < -slop) || (x > (decorView.getWidth() + slop))
                || (y > (decorView.getHeight() + slop));
    }

}

  示例中采用了Java 8的语法编写:在Android中使用Java 8特性

public class MainActivity extends AppCompatActivity {

    private TextView what;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        what = (TextView) findViewById(R.id.what);
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(this::showConfirmDialog);
    }

    private void showConfirmDialog(View view) {
        BaseDialog dialogBase = new BaseDialog(this);
        View warmView = getLayoutInflater().inflate(R.layout.dialog_warm, null);
        ViewGroup parent = (ViewGroup) warmView.getParent();
        if (parent != null) {
            parent.removeAllViews();
        }
        dialogBase.setIcon(R.mipmap.comfirm);
        dialogBase.setTitle(R.string.complete_inv);
        TextView tv = warmView.findViewById(R.id.content);
        tv.setText(R.string.confirm_info);
        tv.setTextColor(getResources().getColor(R.color.colorPrimary));
        dialogBase.setView(warmView);
        dialogBase.setOnKeyListener((dialog, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                if (dialogBase.isShowing()) {
                    dialog.cancel();
                    stop();
                    return true;
                }
            }
            return false;
        });
        dialogBase.setButton(android.app.AlertDialog.BUTTON_NEGATIVE, getString(R.string.cancel),
                (dialog, which) -> stop());
        dialogBase.setBaseDialogListener(this::stop);
        dialogBase.setButton(android.app.AlertDialog.BUTTON_POSITIVE, getString(R.string.confirm),
                (dialog, which) -> {
                    Toast.makeText(this, "确定", Toast.LENGTH_SHORT).show();
                    stop();
                });
        dialogBase.show();
        start();
    }

    private void stop() {
        what.setText("关闭咯~");
    }

    public void start() {
        what.setText("开始咯~");
    }

}

  这里写图片描述
  主要包含了四个监听:(具体请自行试用)

  • 触摸Dialog外部事件监听
  • 确定按钮事件监听
  • 取消按钮事件监听
  • 返回键按键事件监听

  示例下载地址:点我下载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值