【发布时间】:2012-09-20 12:41:34
【问题描述】:
我需要动态居中布局,但问题是我使用 inflate 方法添加布局。我希望按钮居中。
我尝试添加 xml 属性,例如重力、layout_gravity。但它没有用。 我尝试添加参数,但由于我膨胀了 xml,我无法添加参数。因为我不能使用 addRule 方法。
然后我尝试通过将重力属性添加到根布局来使每个元素居中,但也没有成功。
这是我的代码。
actvity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<SurfaceView
android:id="@+id/surfaceView1"
android:layout_width="match_parent"
android:layout_height="335dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:id="@+id/buttons_layout"
android:layout_below="@+id/surfaceView1"
>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="29dp"
android:text="Button" />
</RelativeLayout>
</RelativeLayout>
three_buttons_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/LinearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="29dp"
android:text="Button 1" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="29dp"
android:text="Button 2" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 3" />
</LinearLayout>
这是我的java代码
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
parent = (ViewGroup)findViewById(R.id.buttons_layout);
captureButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
camera.takePicture(null, null, photoCallback);
captureButton.setVisibility(View.GONE);
inflater.inflate(R.layout.three_buttons_layout, parent, true);
}
});
我希望 Button1、Button2 和 Button3 居中。
【问题讨论】:
-
给你的 LinearLayout android:layout_width="fill_parent"
-
您希望按钮水平居中还是屏幕居中?
-
我希望它们水平居中。
-
@PadmaKumar 我给了它 android:layout_width="fill_parent" 但它没有用。还是和截图一样。
标签: java android android-layout layout-inflater