Dialog布局有Edittext的情况下,自动弹出软键盘

1.继承V4包下的DialogFragment,在onCreate方法设置主题

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setStyle(STYLE_NORMAL, R.style.MyEditTextDialogStyle);//设置主题
}

2.Dialog的主题

3.将dialog的重心放在底部

@Override
public void onStart() {
    super.onStart();
    Window window = getDialog().getWindow();
    if (window != null) {
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        WindowManager.LayoutParams attributes = window.getAttributes();
        attributes.gravity = Gravity.BOTTOM;//重心在底部
        attributes.width = WindowManager.LayoutParams.MATCH_PARENT;//宽度填充屏幕
        window.getDecorView().setPadding(0, 0, 0, 0);
        window.setAttributes(attributes);
    }
}

4.代码示例

public class EditTextDialog extends DialogFragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View inflate = inflater.inflate(R.layout.dialog_edittext, container, false);
        return inflate;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(STYLE_NORMAL, R.style.MyEditTextDialogStyle);
    }

    @Override
    public void onStart() {
        super.onStart();
        Window window = getDialog().getWindow();
        if (window != null) {
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            WindowManager.LayoutParams attributes = window.getAttributes();
            attributes.gravity = Gravity.BOTTOM;
            attributes.width = WindowManager.LayoutParams.MATCH_PARENT;
            window.getDecorView().setPadding(0, 0, 0, 0);
            window.setAttributes(attributes);
        }
    }
}

5.使用

EditTextDialog editTextDialog = new EditTextDialog();
editTextDialog.show(getSupportFragmentManager(), null);

你可能感兴趣的:(android,dialog)