您的位置:首页 > 移动开发 > Android开发

Android中 android:gravity 和 android:layout_gravity的区别

2016-10-24 17:59 232 查看
转载  http://blog.csdn.net/jdsjlzx/article/details/50710228

1.android:gravity  

android:gravity 常用于控制view的内部控件或者内容的位置,类似于于padding,如下所示:

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right" //控制EditText控件的位置居右
android:orientation="vertical">

<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:gravity="center" //控制EditText控件的文本的位置居中
android:text="input text" />

</LinearLayout>



下面代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">

<LinearLayout
<span style="color:#ff0000;">android:layout_width="match_parent"
android:layout_height="wrap_content"</span>
android:gravity="right"
android:orientation="vertical">

<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:gravity="center"
android:text="input text" />

</LinearLayout>

</LinearLayout>



在根节点布局中使用了android:gravity="center",影响了里面的view中的位置,不难发现,第二个LinearLayout设置了android:layout_width="match_parent",位置没有受到影响,设置了android:layout_height="wrap_content",第二个LinearLayout就垂直居中了。

2.android:layout_gravity

android:layout_gravity使用的时候一般都要有上级布局,也就是不能用于根节点,如下代码所示:

Java代码来设置组件的位置(参考http://blog.csdn.NET/feng88724)

Button button = new Button(this);
button.setText("One");
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
//此处相当于布局文件中的Android:layout_gravity属性
lp.gravity = Gravity.RIGHT;
button.setLayoutParams(lp);
//此处相当于布局文件中的Android:gravity属性
button.setGravity(Gravity.CENTER);

LinearLayout linear = new LinearLayout(this);
//注意,对于LinearLayout布局来说,设置横向还是纵向是必须的!否则就看不到效果了。
linear.setOrientation(LinearLayout.VERTICAL);
linear.addView(button);
setContentView(linear);
Button button  = new Button(this);
button.setText("One");
//此处相当于布局文件中的Android:gravity属性
button.setGravity(Gravity.CENTER);

LinearLayout linear = new LinearLayout(this);
//注意,对于LinearLayout布局来说,设置横向还是纵向是必须的!否则就看不到效果了。
linear.setOrientation(LinearLayout.VERTICAL);

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
//此处相当于布局文件中的Android:layout_gravity属性
lp.gravity = Gravity.RIGHT;

linear.addView(button, lp);
setContentView(linear);


另外,要设置在RelativeLayout中的位置时使用addRule方法,如下:

[java] view
plain copy

 print?

params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);  

        params.addRule(RelativeLayout.CENTER_IN_PARENT);  

        mContainer.addView(progress,params);  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: