动态改变代码布局

代码

为了满足某些奇葩的需求,我们可以动态改变代码布局,写个demo:DynamicChangeLayout

主要代码如下

    Button btn;
    TextView textView;
    boolean matchParent = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button) findViewById(R.id.btn);
        textView = (TextView) findViewById(R.id.text);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeLayout();
            }
        });
    }

    private void changeLayout() {
        matchParent = !matchParent;
        int height = matchParent ? LinearLayout.LayoutParams.MATCH_PARENT : 150;
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, height);
        textView.setLayoutParams(params);

    }

<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">


    <Button

        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="动态改布局" />


    <LinearLayout
        android:id="@+id/view1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/btn"
        android:orientation="vertical">

        <TextView
            android:id="@+id/text"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#ff00cc"
            android:text="文字" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#00ff00"
            android:text="图片" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#00ffff"
            android:text="位置" />
    </LinearLayout>
</RelativeLayout>


注意几点:

1、textView.setLayoutParams会去调requestLayout,重新measure,重新layout

2、textView.setLayoutParams会导致代码里写的margin无效,所以此处如果要加margin的化得再代码里设置margin,leftMargin,rightMargin这些都是public的成员,可以直接去读写

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值