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