【问题标题】:Why TextView.getHeight() gives different values?为什么 TextView.getHeight() 给出不同的值?
【发布时间】:2018-01-03 13:24:55
【问题描述】:

我有一个应用程序,其中包含一个 textView 和一个 Button,当调用 onCreate 时,我调用 textView.getHeight() 并且返回的值为 0。(在 onResume 和 onPostResume 中也试过这个)。

当用户单击按钮时,它会再次调用 textView.getHeight(),现在我得到的答案是 864 而不是 0。 为什么会这样?

(布局只有一个TextView和一个Button——父级是RelativeLayout)

edit:TextView在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();
        }
    }
}

【问题讨论】:

  • 在 onCreate 视图中不是绘制的。使用View.post()
  • 你能解释一下如何使用“View.post()”吗?

标签: android textview


【解决方案1】:

使用这个

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

        }

它应该可以工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-31
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 2014-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多