activity 中獲取控件的寬高
阿新 • • 發佈:2017-12-25
post oncreate div ams getheight width 方式 return override
1.第一種方式:
TextView textview3 = findViewById(R.id.textview3); textView3.post(new Runnable() { @Override public void run () { int width = textView3.getWidth(); ViewGroup.LayoutParams layoutParams = button2.getLayoutParams(); layoutParams.width= width; button2.setLayoutParams(layoutParams); } });
view的post方法,runnable對象中的方法會在View的measure、layout等事件後觸發UI事件隊列會按順序處理事件。在setContentView()被調用後,事件隊列中會包含一個要求重新layout的message,所以任何你post到隊列中的東西都會在Layout發生變化後執行。
activity中先這行oncreate,然後才是第一次調用onmeasure,
2.第二種方式,同過treeobserve
firstTxt = (TextView) findViewById(R.id.hello_word_txt); ViewTreeObserver viewTreeObserver = firstTxt.getViewTreeObserver(); viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() {int height = firstTxt.getHeight(); int width = firstTxt.getWidth(); Log.v("獲取TextView寬高", "寬度:" + width + ",高度:" + height); return true; } });
activity 中獲取控件的寬高