【问题标题】:How do I get the view of a Tab in a TabLayout?如何在 TabLayout 中获取选项卡的视图?
【发布时间】:2015-10-20 20:33:00
【问题描述】:

我想在 TabLayout 中找到 Tab 的视图,以便将其传递给另一个函数。我不知道如何去寻找视图。 myTabLayout.getTabAt(0).getCustomView() 返回空值。

如何获得视图?

TabLayout tabLayout = (TabLayout) rootView.findViewById(R.id.tab_layout_main);
tabLayout.addTab(tabLayout.newTab().setText("Page1"));
tabLayout.addTab(tabLayout.newTab().setText("Page2"));

viewPager = (ViewPager) rootView.findViewById(R.id.pager_main);
pagerAdapter = new MyPagerAdapter(getActivity(), getChildFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(pagerAdapter);

【问题讨论】:

    标签: android android-layout android-tabs android-tablayout


    【解决方案1】:

    我最终使用以下方法来获取标签视图。我只是不确定这是否是最佳做法,或者它在所有 Android 版本中是否可靠:

    mainTab = ((ViewGroup) tabLayout.getChildAt(0)).getChildAt(desiredPosition);
    

    查看源代码,我们可以看到tabLayout.getChildAt(0) 返回SlidingTabStrip,这是一个扩展LinearLayout 的内部类,用于保存选项卡视图。然后,您可以使用.getChildAt(desiredPosition) 访问选项卡视图。请注意,使用getChildAt() 时,不会检查边界,因此请确保您调用了正确的索引并检查null 返回。

    【讨论】:

    • 嗯,这有帮助。谢谢
    • 虽然这对我有用,但在生产应用程序中使用它之前我会犹豫。如果 Google 更改了 Tab 布局功能,可能会在未来引起一些麻烦。由于它主要是私有的,因此很有可能。
    • 如何把文本视图取出来?我需要在 onCreate 中更改样式?
    【解决方案2】:
        TabLayout tabLayout = .... (findview or code creation )
        /** get selected tab index */
        int selectedTabPosition = tabLayout.getSelectedTabPosition();
        /** get tab for selected index or if u want any other tab set desired index */
        TabLayout.Tab tabAt = tabLayout.getTabAt(selectedTabPosition);
        /** get view - but first u need set custom view on tabl via Tab.setCustomView(View) */
        View tabView = tabAt.getCustomView():
    

    提示:

    • 如果您使用ViewPager 填充TabLayout,请先检查视图是否布局:)。如果没有为ViewPager 设置onLayoutChangedListener,则使用寻呼机设置!

    Tab 如果你想使用反射源:D

    /**
    * A tab in this layout. Instances can be created via {@link #newTab()}.
    */
    public static final class Tab {
        /**
         * An invalid position for a tab.
         *
         * @see #getPosition()
         */
        public static final int INVALID_POSITION = -1;
        private Object mTag;
        private Drawable mIcon;
        private CharSequence mText;
        private CharSequence mContentDesc;
        private int mPosition = INVALID_POSITION;
        private View mCustomView;
        private final TabLayout mParent;
    
        Tab(TabLayout parent) {
            mParent = parent;
        }
    
        /**
         * @return This Tab's tag object.
         */
        @Nullable
        public Object getTag() {
            return mTag;
        }
    
        /**
         * Give this Tab an arbitrary object to hold for later use.
         *
         * @param tag Object to store
         * @return The current instance for call chaining
         */
        @NonNull
        public Tab setTag(@Nullable Object tag) {
            mTag = tag;
            return this;
        }
    
        /**
         * Returns the custom view used for this tab.
         *
         * @see #setCustomView(View)
         * @see #setCustomView(int)
         */
        @Nullable
        public View getCustomView() {
            return mCustomView;
        }
    
        /**
         * Set a custom view to be used for this tab.
         * <p>
         * If the provided view contains a {@link TextView} with an ID of
         * {@link android.R.id#text1} then that will be updated with the value given
         * to {@link #setText(CharSequence)}. Similarly, if this layout contains an
         * {@link ImageView} with ID {@link android.R.id#icon} then it will be updated with
         * the value given to {@link #setIcon(Drawable)}.
         * </p>
         *
         * @param view Custom view to be used as a tab.
         * @return The current instance for call chaining
         */
        @NonNull
        public Tab setCustomView(@Nullable View view) {
            mCustomView = view;
            if (mPosition >= 0) {
                mParent.updateTab(mPosition);
            }
            return this;
        }
    
        /**
         * Set a custom view to be used for this tab.
         * <p>
         * If the inflated layout contains a {@link TextView} with an ID of
         * {@link android.R.id#text1} then that will be updated with the value given
         * to {@link #setText(CharSequence)}. Similarly, if this layout contains an
         * {@link ImageView} with ID {@link android.R.id#icon} then it will be updated with
         * the value given to {@link #setIcon(Drawable)}.
         * </p>
         *
         * @param layoutResId A layout resource to inflate and use as a custom tab view
         * @return The current instance for call chaining
         */
        @NonNull
        public Tab setCustomView(@LayoutRes int layoutResId) {
            return setCustomView(
                    LayoutInflater.from(mParent.getContext()).inflate(layoutResId, null));
        }
    
        /**
         * Return the icon associated with this tab.
         *
         * @return The tab's icon
         */
        @Nullable
        public Drawable getIcon() {
            return mIcon;
        }
    
        /**
         * Return the current position of this tab in the action bar.
         *
         * @return Current position, or {@link #INVALID_POSITION} if this tab is not currently in
         * the action bar.
         */
        public int getPosition() {
            return mPosition;
        }
    
        void setPosition(int position) {
            mPosition = position;
        }
    
        /**
         * Return the text of this tab.
         *
         * @return The tab's text
         */
        @Nullable
        public CharSequence getText() {
            return mText;
        }
    
        /**
         * Set the icon displayed on this tab.
         *
         * @param icon The drawable to use as an icon
         * @return The current instance for call chaining
         */
        @NonNull
        public Tab setIcon(@Nullable Drawable icon) {
            mIcon = icon;
            if (mPosition >= 0) {
                mParent.updateTab(mPosition);
            }
            return this;
        }
    
        /**
         * Set the icon displayed on this tab.
         *
         * @param resId A resource ID referring to the icon that should be displayed
         * @return The current instance for call chaining
         */
        @NonNull
        public Tab setIcon(@DrawableRes int resId) {
            return setIcon(TintManager.getDrawable(mParent.getContext(), resId));
        }
    
        /**
         * Set the text displayed on this tab. Text may be truncated if there is not room to display
         * the entire string.
         *
         * @param text The text to display
         * @return The current instance for call chaining
         */
        @NonNull
        public Tab setText(@Nullable CharSequence text) {
            mText = text;
            if (mPosition >= 0) {
                mParent.updateTab(mPosition);
            }
            return this;
        }
    
        /**
         * Set the text displayed on this tab. Text may be truncated if there is not room to display
         * the entire string.
         *
         * @param resId A resource ID referring to the text that should be displayed
         * @return The current instance for call chaining
         */
        @NonNull
        public Tab setText(@StringRes int resId) {
            return setText(mParent.getResources().getText(resId));
        }
    
        /**
         * Select this tab. Only valid if the tab has been added to the action bar.
         */
        public void select() {
            mParent.selectTab(this);
        }
    
        /**
         * Returns true if this tab is currently selected.
         */
        public boolean isSelected() {
            return mParent.getSelectedTabPosition() == mPosition;
        }
    
        /**
         * Set a description of this tab's content for use in accessibility support. If no content
         * description is provided the title will be used.
         *
         * @param resId A resource ID referring to the description text
         * @return The current instance for call chaining
         * @see #setContentDescription(CharSequence)
         * @see #getContentDescription()
         */
        @NonNull
        public Tab setContentDescription(@StringRes int resId) {
            return setContentDescription(mParent.getResources().getText(resId));
        }
    
        /**
         * Set a description of this tab's content for use in accessibility support. If no content
         * description is provided the title will be used.
         *
         * @param contentDesc Description of this tab's content
         * @return The current instance for call chaining
         * @see #setContentDescription(int)
         * @see #getContentDescription()
         */
        @NonNull
        public Tab setContentDescription(@Nullable CharSequence contentDesc) {
            mContentDesc = contentDesc;
            if (mPosition >= 0) {
                mParent.updateTab(mPosition);
            }
            return this;
        }
    
        /**
         * Gets a brief description of this tab's content for use in accessibility support.
         *
         * @return Description of this tab's content
         * @see #setContentDescription(CharSequence)
         * @see #setContentDescription(int)
         */
        @Nullable
        public CharSequence getContentDescription() {
            return mContentDesc;
        }
    }
    

    或者你可以直接挂钩(通过反射):

    private final SlidingTabStrip mTabStrip;
    

    或者您可以自行决定复制源代码并更改方法和字段。

    【讨论】:

    • 不幸的是,这让我得到了Tab,而不是与选项卡关联的视图。
    • @NSouth - 选项卡布局 - 寻呼机内容上方是什么 - 寻呼机内容是片段 - 你想要寻呼机内容还是选项卡内容?见编辑
    • 谢谢,这是一个非常有用的答案。是的,我想要标签的视图(不是寻呼机片段内容)。这是我发现可行的方法,但我不确定它是否是最佳实践。 mainTab = ((ViewGroup) tabLayout.getChildAt(0)).getChildAt(0);。我不能使用getCustomView(),因为我从未设置自定义视图。但是,如果需要,我可以扩展自己的课程。
    • getCustomView() 返回的 mCustomView 为 null,除非您之前已分配它
    【解决方案3】:

    它返回null,因为您首先没有使用任何自定义视图。它仅在您使用时返回自定义视图。要使用自定义视图,您的代码应该是这样的。

    tabLayout.addTab(tabLayout.newTab().setCustomView(R.layout.custom_view).setText("Page1"));
    

    如果您使用上述行然后尝试调用myTabLayout.getTabAt(0).getCustomView(),它将返回您设置的视图。

    【讨论】:

    • 我认为是这样,但我不想使用自定义视图。我想使用默认视图。
    【解决方案4】:

    回答以供将来参考。

    tabLayout.getTabAt(tabIndex).view

    示例- 获取 tabLayout 中第一个选项卡的视图。使用 tabLayout.getTabAt(0).view

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-19
      • 1970-01-01
      • 2015-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-18
      相关资源
      最近更新 更多