代码
为了满足某些奇葩的需求,我们可以动态改变代码布局,写个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的成员,可以直接去读写