LinearLayout layout_weight和weight_sum用于调整大小?

时间:2013-01-24 22:59:05

标签: android android-layout android-layout-weight

我有5个LinearLayouts。为了便于编写和理解,我将它们称为视图A-E。

视图A是视图B,C,D和E的父级。

我已将视图A的layout_weight设置为8.0f,视图B-E的权重设置为1.0f,3.0f,1.0f,3.0f。

我知道这是用于管理父视图中的空白区域,但我希望将我的视图和子视图的大小设置为拥有屏幕的百分比,而不是仅仅争夺可用空间。

但是,这一切都是以编程方式完成的,所以我应该将LinearLayouts的高度设置为其父级(View A)的getHeight()方法/访问者的系数吗?如果是这样,那么如果视图尚未添加到它的父级,我将如何获得父级的高度,这将使用MATCH_PARENT设置其高度?

由于getHeight()方法将为onCreateonStart和第一个onResume返回0,我必须继续寻找答案。我找到了ViewTreeObserverOnGlobalLayoutListener,它会在设置Layout时通知我。但是,我真的很感激在任何绘图发生前都有高度。这不可能吗?

3 个答案:

答案 0 :(得分:2)

如果您不需要以编程方式执行此操作,则可以在xml中执行此操作。为了让子LinearLayouts占用Parent LinearLayout(LinearLayout A)的百分比,您需要设置父的weightSum =(子LinearLayouts的总layout_weight),然后将子LinearLayouts width / height属性设置为“0dip”并且将layout_weight设置为所需的百分比。

垂直方向的示例代码为:

<LinearLayout
     android:id="@+id/A"
     android:layout_height="fill_parent"
     android:layout_width="fill_parent"
     android:weightSum="8.0"
     android:orientation="vertical">
     <LinearLayout
          android:id="@+id/B"
          android:layout_height="0dip"
          android:layout_width="fill_parent"
          android:layout_weight="1.0"/>
     <LinearLayout
          android:id="@+id/C"
          android:layout_height="0dip"
          android:layout_width="fill_parent"
          android:layout_weight="3.0"
</LinearLayout>

答案 1 :(得分:1)

不幸的是,在绘制之前不可能获得视图的大小(除非有一个我不知道的黑客)。该视图在其准备布局之前不会保留有关其大小的任何信息。如果在未来的版本中,他们设计的系统在绘制视图之前保持视图尺寸,那将是很好的。

您可以创建自定义类,扩展View类,然后覆盖系统调用的方法,并将维返回到活动中的对象引用。然而,这可能是一个令人头疼的问题,而不是真正的优势。

我建议使用ViewTreeObserver和OnGlobalLayoutListener。

答案 2 :(得分:1)

以下是如上所述使用Fragments执行此操作的方法。

首先在onAttach方法中保存对上下文的引用(无论如何,您可能希望设置对该活动的回调:

Context context;

@Override
public void onAttach(Activity activity){
    super.onAttach(activity);

    context = activity;


} 

然后在onViewCreate中,您进行测量并使用它们:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    Display display = ((WindowManager)
        context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    DisplayMetrics metrics = new DisplayMetrics();
    display.getMetrics(metrics);

    float pixHeight = metrics.heightPixels;
    float pixWidth = metrics.widthPixels;
    float density  = context.getResources().getDisplayMetrics().density;
    float dpHeight = pixHeight / density;
    float dpWidth  = pixWidth / density;

    // make various layouts using your measurements, send the
    // measure of each parent to each custom drawn child, or 
    // send the bounds of each child as determined by the size of each parent

    return someView;
}