開發(fā)中經(jīng)常遇到要在oncreate()中獲取控件寬高仔涩,一般的 view.getwidth()總是獲取到的值為零,怎樣才能在oncreate()中處理獲得控件寬高呢蛹锰,下面具體講講深胳。
本篇文章參考以下鏈接:
android獲取屏幕寬高與獲取控件寬高
在此表示感謝!
直接上獲取控件寬高方法的代碼吧铜犬,
/**
* Instruction:控件相關(guān)工具類
* <p>
* Author:pei
* Date: 2017/7/3
* Description:
*/
public class ViewUtil {
public static void getViewWidth(final View view, final OnViewListener onViewListener) {
ViewTreeObserver vto2 = view.getViewTreeObserver();
vto2.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
if(onViewListener!=null){
onViewListener.onView(view.getWidth(),view.getHeight());
}
}
});
}
public interface OnViewListener {
void onView(int width,int height);
}
}
在MainActivity的OnCreate()中的調(diào)用如下:
TextView textView=(TextView)findViewById(R.id.textView);
ViewUtil.getViewWidth(textView, new ViewUtil.OnViewListener() {
@Override
public void onView(int width, int height) {
//執(zhí)行邏輯代碼
//......
}
});
ok,其實獲取控件寬高的代碼并不難舞终,之前也整理過,以為寫過文章呢癣猾,結(jié)果在csdn上翻翻沒有敛劝,就再記錄下,算是筆記吧纷宇,方便以后查閱夸盟,謝謝誒。