【问题标题】:Setting a max width for LinearLayout为 LinearLayout 设置最大宽度
【发布时间】:2011-04-11 17:56:48
【问题描述】:

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

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

【问题讨论】:

  • 查看我的回答 here 了解使用 ViewGroup 子类的另一种方法

标签: android user-interface layout


【解决方案1】:

这样做 - 我需要 beyond what was suggested in prior answer 是添加另一个布局 (@+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>

【讨论】:

  • 不错!像魅力一样工作。
【解决方案2】:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int widthMaxSpec = MeasureSpec.makeMeasureSpec(270 /*pixels*/, MeasureSpec.AT_MOST);
    super.onMeasure(widthMaxSpec, heightMeasureSpec);
}

【讨论】:

  • 欢迎来到 SO,您最好解释一下为什么您的代码可以解决他的问题,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-19
  • 2011-02-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多