How to make the switch button center in dialog

↘锁芯ラ 提交于 2019-12-13 07:09:40

问题


I want to switch button center in dialog,but it's failed...

Why is this?

Switch sw = new Switch(MainActivity.this);
sw.setTextOn("start");
sw.setTextOff("close");
sw.setGravity(Gravity.CENTER_HORIZONTAL);

AlertDialog.Builder myDialog = new AlertDialog.Builder(MainActivity.this);
myDialog.setTitle("title");
myDialog.setMessage("message");
myDialog.setView(sw);


回答1:


Try with below code

        Switch sw = new Switch(MainActivity.this);
        sw.setTextOn("start");
        sw.setTextOff("close");


        LinearLayout linearLayout = new LinearLayout(MainActivity.this);
        linearLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT));
        linearLayout.setGravity(Gravity.CENTER_HORIZONTAL);
        linearLayout.addView(sw);


        AlertDialog.Builder myDialog = new    AlertDialog.Builder(MainActivity.this);
        myDialog.setTitle("title");
        myDialog.setMessage("message");
        myDialog.setView(linearLayout);


        myDialog.show();



回答2:


Use the custom_layout instead.

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center">

           <android.support.v7.widget.SwitchCompat
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
</LinearLayout>

Use LayoutInflater to inflate the layout in dialog

View v = LayoutInflater.from(getActivity()).inflate(R.layout.custom_layout, null);
myDialog.setView(v);



回答3:


Use RelativeLayout instead, set android:centerInParent=true for SwitchButton



来源:https://stackoverflow.com/questions/34061064/how-to-make-the-switch-button-center-in-dialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!