Android 在Activity中獲取控制元件尺寸的方法
阿新 • • 發佈:2019-02-09
上Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/tv_hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</LinearLayout>
上Activity,幾種方法都寫下來了:
package com.cn.measure;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.TextView;
import android.widget.Toast;
@SuppressLint("NewApi")
public class MainActivity extends Activity
{
private TextView tv_hello;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_hello = (TextView)findViewById(R.id.tv_hello);
getSizeWithViewTreeObserver();
getSizeWithPost();
getSizeWithMeasureByHand();
}
/**
* 如果tv_hello的mode是match_parent不能用這種方法
* 因為view的measure過程中需要知道父容器的剩餘空間大小,這個時候無法知道父容器剩餘空間大小
* 其實這種方法不推薦使用,測量出來的值可能不正確
*/
private void getSizeWithMeasureByHand()
{
tv_hello.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
int height = tv_hello.getMeasuredHeight();
int width = tv_hello.getMeasuredWidth();
Toast.makeText(MainActivity.this,
"getSizeWithMeasureByHand excuted: width is " + width + " \n Height is " + height,
0).show();
}
private void getSizeWithPost()
{
tv_hello.post(new Runnable()
{
@Override
public void run()
{
int width = tv_hello.getMeasuredWidth();
int height = tv_hello.getMeasuredHeight();
Toast.makeText(MainActivity.this,
"getSizeWithPost excuted: width is " + width + " \n Height is " + height,
0).show();
}
});
}
private void getSizeWithViewTreeObserver()
{
ViewTreeObserver observer = tv_hello.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener()
{
@Override
public void onGlobalLayout()
{
tv_hello.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int width = tv_hello.getMeasuredWidth();
int height = tv_hello.getMeasuredHeight();
Toast.makeText(MainActivity.this,
"getSizeWithViewTreeObserver excuted: width is " + width + " \n Height is " + height,
0).show();
}
});
}
@Override
public void onWindowFocusChanged(boolean hasFocus)
{
super.onWindowFocusChanged(hasFocus);
int width = tv_hello.getMeasuredWidth();
int height = tv_hello.getMeasuredHeight();
Toast.makeText(MainActivity.this,
"onWindowFocusChanged excuted: width is " + width + " \n Height is " + height,
0).show();
}
}
四種方法:
private void getSizeWithMeasureByHand() //不推薦使用
private void getSizeWithViewTreeObserver() //推薦使用
private void getSizeWithPost() //推薦使用
public void onWindowFocusChanged(boolean hasFocus) //推薦使用