@MasterLeng
2015-06-25T07:03:28.000000Z
字数 1246
阅读 3933
动态设置控件的高度以及在父控件里的位置
android
布局
首先是ImageView设置宽度和高度,整个Activity的布局文件如下,注意最外层是Relativelayout哦~
<!-- lang: java -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ImageView
android:id="@+id/imgTest"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<LinearLayout
android:id="@+id/llTest"
android:layout_below="@+id/imgTest"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
</LinearLayout>
首先,先获得ImageView,以及确定屏幕的宽度和高度
ImageView imgTest = (ImageView)findViewById(R.id.imgTest);
DisplyMetrics dm = getResources().getDisplayMetrics();
int screenWidth = dm.widthPixels();
int screenHeight = dm.heightPixels();
我们有两种方式可以动态设置这个ImageView的宽度和高度:
第一种:
ViewGroup.LayoutParams lp = imgTest.getLayoutParams();
lp.width = screenWidth/2;
lp.height = scrrenHeight/2;
lp.setLayoutParams(lp);
第二种:
RelativeLayout.LayoutParams rllp = new RelativeLayout.LayoutParams(screenWidth/2,screenHeight/2);
rllp.setLayoutParams(rllp);
在编写的时候,我发生了一个错误,就是rllp使用LinearLayout来定义的,导致了类的转换错误。
所以我们可以就此来得出一个结论,ImageView的容器是由父容器来得到并进行相应的设置,因此在开发中我们必须注意空间所在父容器的类型,来进行相应的操作,相应的,第一种出错的概率低很多。