为什么TextView.getHeight()给出不同的值?

时间:2018-01-03 13:24:56

标签: android textview

我有一个带有textView和Button的应用程序,当调用onCreate时,我调用textView.getHeight()并返回的值为0.(在onResume和onPostResume中也尝试了这一点。)

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

(布局只有TextView和Button - 父级是RelativeLayout)

编辑: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();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

使用此

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

        }

应该有效