如何使Android LinearLayout剪辑其子内容



我有一个线性布局(水平),里面有几个子文本视图。我已经为线性布局和所有文本视图设置了固定layout_width。当子项的总宽度超过布局的宽度时,它会自动缩小子项,使它们变窄,这不是我想要的。我希望布局能够剪辑子内容并保持其宽度。我怎样才能做到这一点?

例如:假设我的 LinearLayout 是 200dp 宽,并且有 4 个 TextView,每个 60dp 宽。我希望它显示前三个文本视图,以及第 4 个文本视图的 1/3(60 + 60 + 60 + 20 = 200)

谢谢。

  • LinearLayout中使用android:weightSum

  • 并在TextView中使用android:layout_width="0dp"android:layout_weight="1"

试试这个。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:orientation="horizontal"
          android:weightSum="10">
<TextView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="3"
    android:text="hello"/>
<TextView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="3"
    android:text="hello"/>
<TextView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="3"
    android:text="hello"/>
<TextView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="hello"/>
</LinearLayout>

您可以在TextView中将android:layout_width="match_parent"更改为android:layout_width="wrap_content"

编辑

你可以在你的 java 代码中使用 .

您可以自己更改宽度或重量。

private LinearLayout mLinearLayout;
private int viewsCount = 4;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mLinearLayout = (LinearLayout) findViewById(R.id.linearlayout);
    for (int i = 0; i < viewsCount; i++) {
        TextView textView = new TextView(this);
        if(i == viewsCount-1){
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1);
        } else {
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 3);
        }
        mLinearLayout.addView(textView);
    }
}

最新更新