我有一个应用程序,里面有一个textView和一个按钮,当调用onCreate时,我调用textView.getHeight((,返回的值是0。(在onResume和onPostResume中也尝试过这个(。
当用户单击按钮时,它会再次调用textView.getHeight((,现在我得到的答案是864而不是0。为什么会这样?
(布局只有一个文本视图和一个按钮 - 父级是相对布局(
编辑:文本视图在 xml 中具有:android:layout_height="match_parent"(父视图是 RelativeLayout,布局的基本父视图(,因此真实高度必须> 0。
代码:
TextView text;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (AutoScrollingText) findViewById(R.id.text);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
Toast.makeText(this, "text height: " + text.getHeight(), Toast.LENGTH_SHORT).show();
}
@Override
protected void onPostResume() {
super.onPostResume();
Toast.makeText(this, "text height: " + text.getHeight(), Toast.LENGTH_SHORT).show();
}
@Override
public void onClick(View view) {
switch(view.getId()){
case (R.id.button) : {
Toast.makeText(this, "text height: " + text.getHeight(), Toast.LENGTH_SHORT).show();
}
}
}
使用这个
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (AutoScrollingText) findViewById(R.id.text);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
text.post( new Runnuble(){
Toast.makeText(this, "text height: " + text.getHeight(), Toast.LENGTH_SHORT).show();
});
}
它应该工作