Android 为 LinearLayout 设置最大宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3702000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 11:26:14  来源:igfitidea点击:

Setting a max width for LinearLayout

androiduser-interfacelayout

提问by Asahi

How can I set the max width of my horizontal LinearLayout? So if the contents are short (say, some text), the layout shrinks and if the contents are longer, it will not expand more than some max width value.

如何设置水平线的最大宽度LinearLayout?所以如果内容很短(比如一些文本),布局会缩小,如果内容较长,它不会扩展超过某个最大宽度值。

I prefer doing this at the XML level.

我更喜欢在 XML 级别执行此操作。

采纳答案by Asahi

This does it - what I needed beyond what was suggested in prior answeris to add another layout (@+id/TheLayout) as a wrapper between the content and the top layout:

这样做 -除了先前答案中的建议之外,我需要的是添加另一个布局(@+id/TheLayout)作为内容和顶部布局之间的包装器:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" 
android:layout_width="fill_parent"
android:layout_height="wrap_content" 
android:paddingLeft="100dip"
android:paddingRight="100dip">
<LinearLayout android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:id="@+id/TheLayout"
    android:layout_gravity="right">
    <TextView android:id="@+id/TextView01" 
        android:layout_height="wrap_content"
        android:layout_width="fill_parent" 
        android:layout_weight="1"
        android:text="this is my text." 
        android:layout_gravity="center_vertical">
    </TextView>
    <ImageView android:id="@+id/ImageView01"
        android:layout_height="wrap_content" 
        android:background="@drawable/icon"
        android:layout_width="fill_parent">
    </ImageView>
</LinearLayout>
</LinearLayout>

回答by Bill

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int widthMaxSpec = MeasureSpec.makeMeasureSpec(270 /*pixels*/, MeasureSpec.AT_MOST);
    super.onMeasure(widthMaxSpec, heightMeasureSpec);
}