문제

나는 DialogFragment 표시하려면 View 팝업 화면처럼.창은 항상 화면 중앙에 나타납니다.의 위치를 설정하는 방법이 있습니까 DialogFragment 창문?나는 안으로 봤다 소스 코드 그러나 아직 아무것도 찾을 수 없습니다.

도움이 되었습니까?

해결책

Try something like this:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    getDialog().getWindow().setGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP);
    WindowManager.LayoutParams p = getDialog().getWindow().getAttributes();
    p.width = ViewGroup.LayoutParams.MATCH_PARENT;
    p.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE;
    p.x = 200;
    ...
    getDialog().getWindow().setAttributes(p);
    ...

또는 다른 방법 getDialog().getWindow().

을 설정하십시오 위치를 호출한 후에 설정 내용입니다.

다른 팁

른,나는 마막로 기,이 두 시간 동 벽 머리를 부딪 DialogFragment 내가 원하는 것처럼 위치.

나는 위에 건축하고 있다 스틸라이트의 대답 여기요이것은 내가 찾은 가장 간단하고 신뢰할 수있는 접근 방식입니다.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle b) {
    Window window = getDialog().getWindow();

    // set "origin" to top left corner, so to speak
    window.setGravity(Gravity.TOP|Gravity.LEFT);

    // after that, setting values for x and y works "naturally"
    WindowManager.LayoutParams params = window.getAttributes();
    params.x = 300;
    params.y = 100;
    window.setAttributes(params);

    Log.d(TAG, String.format("Positioning DialogFragment to: x %d; y %d", params.x, params.y));
} 

참고: params.width 그리고 params.softInputMode (스틸라이트의 답변에서 사용된)이와는 관련이 없습니다.


아래는 더 완전한 예입니다.내가 정말로 필요한 것은"소스"또는"부모"보기 옆에"확인 상자"대화 상자를 정렬하는 것이 었습니다(내 경우에는 이미지 버튼).

나는 당신에게 무료로"대화 상자"기능을 제공하기 때문에 사용자 정의 조각 대신 대화 상자를 사용하기로 결정했습니다(사용자가 외부를 클릭 할 때 대화 상자 닫기 등).

Example ConfirmBox
"소스"이미지 버튼 위의 확인 상자 예(휴지통)

/**
 * A custom DialogFragment that is positioned above given "source" component.
 *
 * @author Jonik, https://stackoverflow.com/a/20419231/56285
 */
public class ConfirmBox extends DialogFragment {
    private View source;

    public ConfirmBox() {
    }

    public ConfirmBox(View source) {
        this.source = source;            
    }

    public static ConfirmBox newInstance(View source) {
        return new ConfirmBox(source);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setStyle(STYLE_NO_FRAME, R.style.Dialog);
    }


    @Override
    public void onStart() {
        super.onStart();

        // Less dimmed background; see https://stackoverflow.com/q/13822842/56285
        Window window = getDialog().getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        params.dimAmount = 0.2f; // dim only a little bit
        window.setAttributes(params);

        // Transparent background; see https://stackoverflow.com/q/15007272/56285
        // (Needed to make dialog's alpha shadow look good)
        window.setBackgroundDrawableResource(android.R.color.transparent);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Put your dialog layout in R.layout.view_confirm_box
        View view = inflater.inflate(R.layout.view_confirm_box, container, false);

        // Initialise what you need; set e.g. button texts and listeners, etc.

        // ...

        setDialogPosition();

        return view;
    }

    /**
     * Try to position this dialog next to "source" view
     */
    private void setDialogPosition() {
        if (source == null) {
            return; // Leave the dialog in default position
        }

        // Find out location of source component on screen
        // see https://stackoverflow.com/a/6798093/56285
        int[] location = new int[2];
        source.getLocationOnScreen(location);
        int sourceX = location[0];
        int sourceY = location[1];

        Window window = getDialog().getWindow();

        // set "origin" to top left corner
        window.setGravity(Gravity.TOP|Gravity.LEFT);

        WindowManager.LayoutParams params = window.getAttributes();

        // Just an example; edit to suit your needs.
        params.x = sourceX - dpToPx(110); // about half of confirm button size left of source view
        params.y = sourceY - dpToPx(80); // above source view

        window.setAttributes(params);
    }

    public int dpToPx(float valueInDp) {
        DisplayMetrics metrics = getActivity().getResources().getDisplayMetrics();
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, metrics);
    }
}

필요에 따라 생성자 매개 변수 또는 세터를 추가하여 위의 더 일반적인 사용을 만드는 것은 매우 쉽습니다.(내 마지막 ConfirmBox 텍스트와 스타일이 지정된 버튼(일부 테두리 내부 등)이 있습니다. View.OnClickListener 코드에서 사용자 정의 할 수 있습니다.)

getDialog().getWindow()DialogFragmentgetWindow() null 을 반환합니다면 호스팅 활동을 보이지 않는,그렇지 않은 경우 쓰기 조각을 포함됩니다.당신을 얻을 것이다 NullPointerException 려고 할 때 getAttributes().

추천 Mobistry 의 대답이다.이미 있는 경우 DialogFragment 클래스에,그것은 너무 어려운 일이 아니다 스위치.대체 onCreateDialog 방법으로는 하나 구문을 반환합 PopupWindow.그럼 당신은 다시 사용할 수 있기를 공급하는 AlertDialog.builder.setView(), 고,전화 (PopupWindow object).showAtLocation().

다음과 같이 DialogFragment에서 Onresume () 메소드를 무시해야합니다.

@Override
public void onResume() {
    final Window dialogWindow = getDialog().getWindow();
    WindowManager.LayoutParams lp = dialogWindow.getAttributes();
    lp.x = 100;        // set your X position here
    lp.y = 200;        // set your Y position here
    dialogWindow.setAttributes(lp);

    super.onResume();
}
.

보기의 위치와 크기를 지정할 수 있기 때문에이 목적을 위해 PopUpWindow 클래스를 사용하고 있습니다.

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Dialog dialog = new Dialog(mActivity, R.style.BottomDialog);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // 
    dialog.setContentView(R.layout.layout_video_live);
    dialog.setCanceledOnTouchOutside(true);

    Window window = dialog.getWindow();
    assert window != null;
    WindowManager.LayoutParams lp = window.getAttributes();
    lp.gravity = Gravity.BOTTOM; //psotion
    lp.width = WindowManager.LayoutParams.MATCH_PARENT; // fuill screen
    lp.height = 280;
    window.setAttributes(lp);
    return dialog;
}
.

AppCompatDialogFragment에서 android.support.v7.app.AppCompatDialogFragment를 사용하고 있으며 대화 상자 조각을 화면 하단에 정렬하고 모든 테두리를 제거하고 특히 부모와 일치하도록 콘텐츠 너비를 설정해야했습니다.

그래서, 나는 이것으로부터 원했다 (노란색 배경은 rootlayout의 rootlayout에서 온다) :

src_img_1

가져 오기 :

src_img_2

해결되지 않은 솔루션은 작동하지 않았습니다.그래서, 나는 이것을 할 수있었습니다 :

fun AppCompatDialogFragment.alignToBottom() {
    dialog.window.apply {
        setGravity(Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL)
        decorView.apply {

            // Get screen width
            val displayMetrics = DisplayMetrics().apply {
                windowManager.defaultDisplay.getMetrics(this)
            }

            setBackgroundColor(Color.WHITE) // I don't know why it is required, without it background of rootView is ignored (is transparent even if set in xml/runtime)
            minimumWidth = displayMetrics.widthPixels
            setPadding(0, 0, 0, 0)
            layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
            invalidate()
        }
    }
}
.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top