如何使对话框中的开关按钮居中

How to make the switch button center in dialog

我想在对话框中切换按钮中心,但是失败了...

这是为什么?

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);

改用custom_layout

<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>

使用LayoutInflater在对话框中扩充布局

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

试试下面的代码

        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();

改为使用 RelativeLayout,为 SwitchButton 设置 android:centerInParent=true