为什么我们应该发布runnable来改变一些观看行为

时间:2015-12-30 09:54:19

标签: java android android-layout material-design

我想知道在某些情况下我们应该发布可运行的更改视图行为。例如,我有一个标签布局,我想决定是否应该根据屏幕大小和tablaylout宽度使其可滚动或固定。这是代码:

mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);
        mViewPager.setCurrentItem(3, true);
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            PersianTextView s = new PersianTextView(getApplicationContext());
            s.setGravity(Gravity.CENTER_HORIZONTAL);
            s.setText(mSectionsPagerAdapter.getPageTitle(i));
            s.setTextColor(Color.WHITE);
            s.setTextSize(TypedValue.COMPLEX_UNIT_SP, getResources().getDimension(R.dimen.size));
            tabLayout.getTabAt(i).setCustomView(s);
        }
        if (tabLayout.getWidth() < UserDetails.this.getResources().getDisplayMetrics().widthPixels) {
            Log.d(TAG, "tabLayout.getMeasuredWidth(): " + tabLayout.getMeasuredWidth() + "  || UserDetails.this.getResources().getDisplayMetrics().widthPixels: " + UserDetails.this.getResources().getDisplayMetrics().widthPixels);
            tabLayout.setTabMode(TabLayout.MODE_FIXED);
        }
上面代码中的

tabLayout.getWidth()返回零。但如果我这样做,它将起作用,因为tabLayout.getWidth()实际上是一个值:

        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);
        mViewPager.setCurrentItem(3, true);
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            PersianTextView s = new PersianTextView(getApplicationContext());
            s.setGravity(Gravity.CENTER_HORIZONTAL);
            s.setText(mSectionsPagerAdapter.getPageTitle(i));
            s.setTextColor(Color.WHITE);
            s.setTextSize(TypedValue.COMPLEX_UNIT_SP, getResources().getDimension(R.dimen.size));
            tabLayout.getTabAt(i).setCustomView(s);
        }
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                if (tabLayout.getWidth() < UserDetails.this.getResources().getDisplayMetrics().widthPixels) {
                    Log.d(TAG, "tabLayout.getMeasuredWidth(): " + tabLayout.getMeasuredWidth() + "  || UserDetails.this.getResources().getDisplayMetrics().widthPixels: " + UserDetails.this.getResources().getDisplayMetrics().widthPixels);
                    tabLayout.setTabMode(TabLayout.MODE_FIXED);
                }
            }
        });

0 个答案:

没有答案