【问题标题】:Linearlayout getHeight() return 0 but inside setOnClickListener return true value [duplicate]Linearlayout getHeight()返回0但在setOnClickListener内部返回真值[重复]
【发布时间】:2017-11-23 22:25:15
【问题描述】:

编辑:本意是问“为什么它在 setOnClickListener 中起作用”,但很快就找到了。 https://stackoverflow.com/a/21926714/6474462

旧: 在玩 ObjectAnimator 时发现 LinearLayout getHeight() 返回 0,但在 setOnClickListener(after click) 内部确实返回了 true 值,这是如何工作的?

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

【问题讨论】:

    标签: android android-linearlayout onclicklistener


    【解决方案1】:

    对象在屏幕上绘制后需要调用 getHeight()

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-31
      • 2021-07-08
      • 2020-01-17
      相关资源
      最近更新 更多