如何刷新RelativeLayout的大小?

时间:2014-07-16 07:11:08

标签: android android-relativelayout

我有RelativeLayout

<RelativeLayout
    android:id="@+id/relativeLayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/textView1"
        android:text="TextView" />
</RelativeLayout>

我想通过点击GONE制作textView2 Button。我想在之前和之后获得RelativeLayout的高度。

我写了这段代码,为此:

Boolean shown = true;
Button btn = (Button) findViewById(R.id.button1);
final TextView tv2 = (TextView) findViewById(R.id.textView2);
final RelativeLayout rl = (RelativeLayout) findViewById(R.id.relativeLayout);
btn.setOnClickListener(new OnClickListener() {  
        @Override
        public void onClick(View v) {
            int saveHeight = rl.getHeight();
            if(shown) {
                tv2.setVisibility(View.GONE);
            }
            else {
                tv2.setVisibility(View.VISIBLE);
            }
            shown = !shown;
            Toast.makeText(getApplicationContext(), saveHeight + " " + rl.getHeight(), Toast.LENGTH_SHORT).show();

        }
    });

我的问题是,当我致电rl.getHeight时,我总是得到旧尺寸。

我已经尝试过使用:

rl.requestLayout();
rl.invalidate();
rl.setVisibility(View.GONE);
rl.setVisibility(View.VISIBLE);

我的问题是:如何刷新RelativeLayout,以便更新高度

2 个答案:

答案 0 :(得分:0)

改变可见度就足够了。但是,布局不是同步测量和布局的。而只是一个&#34;布局请求&#34;消息发布在UI线程消息队列中。检索新大小的一种方法是post()你自己的runnable检索新的大小,例如。

final int saveHeight = ...;
view.setVisibility(View.GONE);
view.post(new Runnable() {
  @Override public void run() {
     int newHeight = ...;
  }
});

答案 1 :(得分:0)

您需要使用ViewTreeObserver。您可以使用它来收听布局更改。

final RelativeLayout rl=(RelativeLayout )findViewById(R.id.relativeLayout);
 ViewTreeObserver vto=.getViewTreeObserver();
 vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

    @Override
    public void onGlobalLayout() {
        // This will always update height
        relHeight=rl.getHeight();
    }
});