2017-06-21 2 views
0

Editer: Cela signifiait "Pourquoi cela fonctionne-t-il dans setOnClickListener", mais il l'a trouvé peu de temps après. https://stackoverflow.com/a/21926714/6474462Linearlayout getHeight() renvoie 0 mais à l'intérieur de setOnClickListener renvoie la valeur true

Old: Jouait avec le ObjectAnimator et le retour remarqué LinearLayout getHeight() 0, mais à l'intérieur du setOnClickListener (après clic) ne renvoient effectivement la valeur réelle, comment cela fonctionne?

public class MainActivity extends AppCompatActivity { 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     final LinearLayout linearLayout = (LinearLayout) findViewById(R.id.main_linear); 

     TextView textView1 = (TextView) findViewById(R.id.textview1); 
     final TextView textView2 = (TextView) findViewById(R.id.textview2); 

     int viewHeight1 = linearLayout.getHeight(); 
     textView1.setText("viewHeight1: " + viewHeight1); 

     textView2.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       int viewHeight2 = linearLayout.getHeight(); 
       textView2.setText("viewHeight2: " + viewHeight2); 
       } 
      }); 
     } 
    } 

Répondre

2

Vous devez appeler getHeight() après que l'objet dessiner à l'écran

final TextView textView1 = (TextView)findViewById(R.id.textview1); 
final ViewTreeObserver object= textView1 .getViewTreeObserver(); 
    object.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
     @Override 
     public void onGlobalLayout() { 
      textView1 .getHeight() 
      object.removeGlobalOnLayoutListener(this); 
     } 
    });