在onCreate()方法中获取textview.getHeight()

时间:2018-09-02 11:12:31

标签: android

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:padding="10dp"
    android:orientation="vertical">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Test"
        android:textSize="20sp"
        android:onClick="aaaa"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:text="text"
        android:id="@+id/tv10"/>
</LinearLayout>

MainActivity

public class MainActivity extends AppCompatActivity {
    private TextView tv10;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv10=(TextView)findViewById(R.id.tv10);
    Toast.makeText(getApplicationContext(), "H: "+tv10.getHeight(), Toast.LENGTH_SHORT).show();
    }
    public void aaaa(View view) {
        Toast.makeText(getApplicationContext(), "H: "+tv10.getHeight(), Toast.LENGTH_SHORT).show();
    }
}

*当我按下“ Test”按钮时,“ tv10.getHeight()”给出了TextView Height的值,但是onCreate()方法“ tv10.getHeight()”给出了TextView Height的0。 * 我需要将TextView Height放入onCreate()方法中

1 个答案:

答案 0 :(得分:0)

请使用此代码:

         textview.post(new Runnable() {
                              public void run() {

                                 int height = textview.getHeight();

                              }
                      });