LinearLayout中权重使用的机会很多,但是几乎都是在布局中将权重比例固定死,这里简单介绍下在代码中动态设置权重比例的方法.
- xml文件中权重使用方式:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="horizontal"
tools:context="com.example.li_yx.demo.MainActivity">
<TextView
android:id="@+id/tv1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#fffadfda"
android:gravity="center"
android:text="Hello World!" />
<TextView
android:id="@+id/tv2"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#dae0fa"
android:gravity="center"
android:text="你好" />
</LinearLayout>
效果图:
- 代码中动态设置权重比例:
public class MainActivity extends AppCompatActivity {
private TextView tv1;
private TextView tv2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = findViewById(R.id.tv1);
tv2 = findViewById(R.id.tv2);
//tv1设置权重是1
LinearLayout.LayoutParams weight1 = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1.0f);
tv1.setLayoutParams(weight1);
tv1.setText("权重为1");
//tv2设置权重是1
LinearLayout.LayoutParams weight2= new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 2.0f);
tv2.setLayoutParams(weight2);
tv1.setText("权重为2");
}
}
效果图:
在xml中使用权重特别需要的地方,在代码中动态设置时同样需要注意,即:
- 如果在给空间设置权重的时候,如果布局中设置的方向是horizontal,那么就在
LayoutParams(0,heignt,weight);- 如果在给空间设置权重的时候,如果布局中设置的方向是vertical,那么就在
LayoutParams(width,0,weight).