查看动态添加视图的宽度

时间:2016-04-06 06:56:55

标签: android

我想显示一个这样的通知计数器:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:gravity="center"
    android:padding="@dimen/_5sdp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:alpha=".5"
        android:id="@+id/gvIcon"
        android:src="@drawable/ic_person_reading"
        android:scaleType="centerCrop"
        android:layout_width="@dimen/_70sdp"
        android:layout_height="@dimen/_70sdp" />

    <LinearLayout
        android:id="@+id/llTexts"
        android:gravity="center_horizontal"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            style="@style/gridItemsText"
            android:id="@+id/gvText"
            android:text="Guten Morgen"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/partNoticeTooltip"
            android:orientation="vertical"
            android:background="@drawable/bg_tooltip_red"
            android:layout_width="@dimen/tooltipWH"
            android:layout_height="@dimen/tooltipWH">

            <TextView
                android:id="@+id/tvCounter"
                android:text="4"
                android:textColor="@color/white"
                android:textSize="@dimen/h6"
                android:gravity="center"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

其输出如下:

enter image description here

这是我的期望,但是以动态的方式。所以我在setOnItemClickListener的{​​{1}}中写了这个:

GridView

View tooltip = context.getLayoutInflater().inflate(R.layout.part_tooltip, null); TextView tvCounter = (TextView) tooltip.findViewById(R.id.tvCounter); tvCounter.setText("" + counter); LinearLayout llText = (LinearLayout) view.findViewById(R.id.llTexts); llText.addView(tooltip); 具有完全相同的代码,但具有另一种布局。这是输出:

enter image description here

红色布局未以全宽显示。我错过了什么?

1 个答案:

答案 0 :(得分:0)

您需要使用全局布局侦听器以及视图树观察器:

ViewTreeObserver mVTO = parentLayoutOfTheViewAddedDynamically.getViewTreeObserver();
    mVTO.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {


        @Override
        public void onGlobalLayout() {

            if(viewAddedDynamically != null){

                int viewWidth = viewAddedDynamically.getWidth();
          //    any operation based on viewWidth is to be done here
            }

        }
    });