Android 布局参数对象LayoutParam的使用

    xiaoxiao2022-06-28  37

    有时候我们需要在代码中动态的改变一个组件的宽高等属性来满足我们的需求, 例如: app中每个界面在请求网络后获取到了空数据, 这个时候我们就要显示相应的布局, 但是如果要显示不同的空布局, 那么就不能简单地写到父类布局中了,应该有子类自己来实现;

    1.第一种情况: 改变已有布局文件某个组件的宽高 先举个栗子:

    TextView tv = (TextView) findViewById(R.id.tv); RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) tv.getLayoutParams(); params.height = 100; params.width = 100; tv.setLayoutParams(params);

    布局文件 :

    <?xml version="1.0" encoding="utf-8"?> <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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="cn.xianzaishi.rxjava.MainActivity"> <TextView android:id="@+id/tv" android:layout_width="match_parent" android:layout_height="300dp" android:background="#ff4400" android:text="Hello World!" /> </RelativeLayout>

    如果find的是framlayout的话, 就可以清除某一个布局, 在把自己想要加的布局添加进入就可以了; framlayout有2个方法, 一个是移除所有view, 一个是移除一个指定view;

    2 代码中new出某个组件并设置宽高

    我们的需求是给framlayout中动态添加一个组件; ImageView imageView = new ImageView(getApplicationContext()); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); FrameLayout.LayoutParams params = new FrameLayout.LayoutPar (FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.MATCH_PARENT); imageView.setLayoutParams(params); imageView.setImageResource(R.mipmap.guide1); imageView.setVisibility(View.VISIBLE); flContainer.addView(imageView);e

    note: FrameLayout.LayoutParams params = new FrameLayout.LayoutParams (FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.MATCH_PARENT);这行代码在你开始new 的时候并不是这样的, 而为什么要用FrameLayout约束呢?这是因为在获取布局参数对象的时候都要根据这个组件的上一个父组件获取;至于什么时候new,什么时候不new? 取决于这个组件是不是从布局文件中获取的, 是的话就是view.getLayoutParam,否的话就是new布局参数;

    转载请注明原文地址: https://ju.6miu.com/read-1124374.html

    最新回复(0)