[英]getHeight(), getWidth() in textView return 0
I want to getHight
and getWidth
of text in textView. 我想在
getHight
中获取文本的getHight
和getWidth
。 I referenced many topics but have not found out my problem yet. 我引用了许多主题,但尚未发现我的问题。 In some topic a see some solutions as:
在某些主题中,可以看到一些解决方案,例如:
@Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
Log.d("line", ""+selectA.getLineCount());
Log.d("hight", "" +selectA.getHeight());
}
OR 要么
TextView upV = (TextView)findViewById(R.id.up);
ViewTreeObserver vto = upV.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Log.d("W ", ""+upV.getWidth());
Log.d("H ", ""+upV.getHeight());
}
});
These solutions get the value as I need but not every time the app run, sometimes it return 0
. 这些解决方案会根据我的需要获取值,但并非每次应用程序运行时都会得到值,有时
return 0
。 Please help me 请帮我
You are calling getWidth()
and getHeight()
too early. 您太早调用
getWidth()
和getHeight()
了。 The UI has not been sized and laid out on the screen yet, and as a result, the methods are correctly returning 0. UI尚未调整大小并在屏幕上布局,因此,方法正确返回0。
To get height or width of a View you can override onDraw(Canvas canvas) of this View: 要获取视图的高度或宽度,可以覆盖此视图的onDraw(Canvas canvas):
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
int w = getWidth();
int h = getHeight();
}
You are getting this because when you are querying the height view is not drawn. 之所以得到这个,是因为在查询时未绘制高度视图。
Solution- 解-
textView.post(new Runnable() {
@Override
public void run() {
//height is ready
int height = textView.getHeight();
}
});
Use below code to get Height and Width of TextView 使用以下代码获取TextView的高度和宽度
textView.measure(0,0)
int w = textView.getMeasuredWidth();
int h = textView.getMeasuredHeight();
I have found a simple ...very simple Solution. 我找到了一个简单的...非常简单的解决方案。
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class SimpleActivity extends Activity {
private TextView textView;
private int displayWidth, displayHeight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView) findViewById(R.id.hello_tv);
textView.setOnClickListener(
new OnClickListener()
{
@Override
public void onClick(View v) {
displayWidth = textView.getWidth();
displayHeight = textView.getHeight();
textView.setText(displayWidth + "\n" + displayHeight);
}
}
);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.