视图层次结构中的额外布局

时间:2014-03-14 10:21:42

标签: android

我在一个活动中有一个自定义视图,我希望拉伸整个屏幕。不幸的是match_parent不起作用。我查看了层次结构,看起来还有额外的线性布局,你可以在这里看到

enter image description here

我不知道为什么第二个线性布局就在那里。我创建这样的视图。

public class TimeSlider extends LinearLayout {

    private TextView timeHandleTv;


    public TimeSlider(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        layoutInflater.inflate(R.layout.time_slider, this, true);
        timeHandleTv = (TextView) findViewById(R.id.timeHandleTv);
    }
}

time_slider.xml看起来像这样。

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent">
    <TextView
        android:id="@+id/timeHandleTv"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:textColor="@color/White"
        android:paddingLeft="10dp"
        android:paddingRight="12dp"
        android:singleLine="true"
        android:textSize="13sp"
        android:background="@drawable/time_handle" />

</LinearLayout>

额外的线性布局来自哪里?

修改

为了更清楚,这个视图只有一个textview。但是,文本视图将移动到线性布局中的不同位置。因此有必要使用linearlayout父级。正如您在此代码中看到的那样

@Override
public boolean onTouchEvent(MotionEvent event) {
    int Y = (int) event.getY();
    if (Y < 1) {
        Y = 0;
    } else if(Y > getHeight() - timeHandleTv.getHeight()) {
        Y =  getHeight() - timeHandleTv.getHeight();
    }
    switch (event.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
            break;
        case MotionEvent.ACTION_UP:
            layoutParams.topMargin = Y;
            timeHandleTv.setLayoutParams(layoutParams);
            timeHandleTv.setText(getTime());
            break;
        case MotionEvent.ACTION_POINTER_DOWN:
            break;
        case MotionEvent.ACTION_POINTER_UP:
            break;
        case MotionEvent.ACTION_MOVE:
            layoutParams.topMargin = Y;
            timeHandleTv.setLayoutParams(layoutParams);
            timeHandleTv.setText(getTime());
            break;
    }
    return true;
}

如果我删除了xml中的linearlayout,我会删除层次结构中的额外linearlayout。但是,如果我在视图中有多个视图,我将如何创建它而不需要额外的linearlayout?

1 个答案:

答案 0 :(得分:0)

当你给布局膨胀时,作为LinearLayout的TimeSlider成为它的父级。在这一行:

layoutInflater.inflate(R.layout.time_slider, this, true);

您要求使用当前对象作为父对象来扩充布局。您在层次结构中看到的是:

  • TimeSlider类布局 - LinearLayout
  • 来自time_slider.xml的LinearLayout
  • 来自time_slider.xml的TextView
相关问题