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;
}
});