Android博客挑错系列之一FragmentTabHost和ViewPager实现底部导航栏

博客文章指出常见实现FragmentTabHost和ViewPager结合的底部导航栏方式会浪费资源,创建过多Fragment实例。提出两种解决方案:自定义底部栏配合ViewPager或重用TabWidget。作者分享了通过修改TabWidget源码创建MartianTabWidget,实现公共的OnTabSelectionChanged接口以简化点击事件处理,并已在实际项目淘小说中应用。

决定写这个系列,是因为大部分的国内博客都是拿来主义——照搬,一点也不考察博客内容的正确性,

希望这个系列能对国内的这种风气起到一点作用。


首先就拿一个常见的FragmentTabHost和ViewPager实现手势切换底部工具栏来开开刀吧

一个实现普遍的实现如博客使用FragmentTabHost和ViewPager实现仿微信主界面侧滑  (无意冒犯,Google搜索的排名靠前,如需删除请告知)

这种实现方法确实能够实现底部工具栏的切换,但是却增加了一倍Fragment的数量。


文中调用FragmentTabHost的addTab将fragmentArray中Fragments加入FragmentTabHost中,

(注:fragment是以class的形式传入,在FragmentTabHost的内部会将这些fragment的类实例化)

而在initPager函数中又新建了一遍所有的fragment,并加入到ViewPager中。

因此文中存在8个fragment的实例,而这个界面往往是放在应用启动后的第一个界面,这种资源的浪费是很严重的。


那么如何解决呢?


一种方法是自己写一个底部的工具栏,然后配合ViewPager进行Tab的切换。

虽然方法简单,但略显繁琐,有点重复造轮子的感脚。


另外一种方法是重用FragmentTabHost中的TabWidget类,具体的xml代码如下:


  


  
    
    
   
        
    
   

       
   


  

TabWidget的具体用法资料比较少,可直接看其源代码TabWidget.java

简单说下,通过TabWidget.addView()来加入Tab的图标,

通过TabWidget.setCurrentTab()来设置当前focus在哪个tab上。


但是这种方法存在两个问题,一个是Tab的点击响应实现不方便,一个是2.3及以下的系统不兼容。

可以看到源码中OnTabSelectionChanged并不是public,因此只有和TabWidget在一个package中的才能访问这个interface。

而不兼容问题导致在应用中TabWidget显示成一个白条。。。


因此小星最后的解决方法是实现自己的一个TabWidget,但并不是完全自己写,而是有选择的拷贝TabWidget里的代码。

最终修改后的TabWidget的源码如下,小星将其命名为MartianTabWidget:

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityEvent;
import android.widget.LinearLayout;

/**
 * Created by xuzb on 14-12-29.
 */
public class MartianTabWidget extends LinearLayout implements View.OnFocusChangeListener {

    private OnTabSelectionChanged mSelectionChangedListener;

    // This value will be set to 0 as soon as the first tab is added to TabHost.
    private int mSelectedTab = -1;

    public MartianTabWidget(Context context) {
        super(context);
        initTabWidget();
    }

    public MartianTabWidget(Context context, AttributeSet attrs) {
        super(context, attrs);
        initTabWidget();
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public MartianTabWidget(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initTabWidget();
    }

    private void initTabWidget() {
        setChildrenDrawingOrderEnabled(true);

        // Deal with focus, as we don't want the focus to go by default
        // to a tab other than the current tab
        setFocusable(true);
        setOnFocusChangeListener(this);
    }

    /**
     * Returns the tab indicator view at the given index.
     *
     * @param index the zero-based index of the tab indicator view to return
     * @return the tab indicator view at the given index
     */
    public View getChildTabViewAt(int index) {
        return getChildAt(index);
    }

    /**
     * Returns the number of tab indicator views.
     * @return the number of tab indicator views.
     */
    public int getTabCount() {
        return getChildCount();
    }

    /**
     * Sets the current tab.
     * This method is used to bring a tab to the front of the Widget,
     * and is used to post to the rest of the UI that a different tab
     * has been brought to the foreground.
     *
     * Note, this is separate from the traditional "focus" that is
     * employed from the view logic.
     *
     * For instance, if we have a list in a tabbed view, a user may be
     * navigating up and down the list, moving the UI focus (orange
     * highlighting) through the list items.  The cursor movement does
     * not effect the "selected" tab though, because what is being
     * scrolled through is all on the same tab.  The selected tab only
     * changes when we navigate between tabs (moving from the list view
     * to the next tabbed view, in this example).
     *
     * To move both the focus AND the selected tab at once, please use
     * {@link #setCurrentTab}. Normally, the view logic takes care of
     * adjusting the focus, so unless you're circumventing the UI,
     * you'll probably just focus your interest here.
     *
     *  @param index The tab that you want to indicate as the selected
     *  tab (tab brought to the front of the widget)
     *
     */
    public void setCurrentTab(int index) {
        if (index < 0 || index >= getTabCount() || index == mSelectedTab) {
            return;
        }

        if (mSelectedTab != -1) {
            getChildTabViewAt(mSelectedTab).setSelected(false);
        }
        mSelectedTab = index;
        getChildTabViewAt(mSelectedTab).setSelected(true);

        if (isShown()) {
            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
        }
    }

    @Override
    protected int getChildDrawingOrder(int childCount, int i) {
        if (mSelectedTab == -1) {
            return i;
        } else {
            // Always draw the selected tab last, so that drop shadows are drawn
            // in the correct z-order.
            if (i == childCount - 1) {
                return mSelectedTab;
            } else if (i >= mSelectedTab) {
                return i + 1;
            } else {
                return i;
            }
        }
    }

    @Override
    public void addView(View child) {
        if (child.getLayoutParams() == null) {
            final LinearLayout.LayoutParams lp = new LayoutParams(
                    0,
                    ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
            lp.setMargins(0, 0, 0, 0);
            child.setLayoutParams(lp);
        }

        // Ensure you can navigate to the tab with the keyboard, and you can touch it
        child.setFocusable(true);
        child.setClickable(true);

        super.addView(child);

        // TODO: detect this via geometry with a tabwidget listener rather
        // than potentially interfere with the view's listener
        child.setOnClickListener(new TabClickListener(getTabCount() - 1));
        child.setOnFocusChangeListener(this);
    }

    @Override
    public void removeAllViews() {
        super.removeAllViews();
        mSelectedTab = -1;
    }

    /**
     * Provides a way for {@link android.widget.TabHost} to be notified that the user clicked on a tab indicator.
     */
    public void setTabSelectionListener(OnTabSelectionChanged listener) {
        mSelectionChangedListener = listener;
    }

    /** {@inheritDoc} */
    public void onFocusChange(View v, boolean hasFocus) {
        if (v == this && hasFocus && getTabCount() > 0) {
            getChildTabViewAt(mSelectedTab).requestFocus();
            return;
        }

        if (hasFocus) {
            int i = 0;
            int numTabs = getTabCount();
            while (i < numTabs) {
                if (getChildTabViewAt(i) == v) {
                    setCurrentTab(i);
                    mSelectionChangedListener.onTabSelectionChanged(i, false);
                    if (isShown()) {
                        // a tab is focused so send an event to announce the tab widget state
                        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
                    }
                    break;
                }
                i++;
            }
        }
    }

    // registered with each tab indicator so we can notify tab host
    private class TabClickListener implements View.OnClickListener {

        private final int mTabIndex;

        private TabClickListener(int tabIndex) {
            mTabIndex = tabIndex;
        }

        public void onClick(View v) {
            mSelectionChangedListener.onTabSelectionChanged(mTabIndex, true);
        }
    }

    /**
     * Let {@link android.widget.TabHost} know that the user clicked on a tab indicator.
     */
    public static interface OnTabSelectionChanged {
        /**
         * Informs the TabHost which tab was selected. It also indicates
         * if the tab was clicked/pressed or just focused into.
         *
         * @param tabIndex index of the tab that was selected
         * @param clicked whether the selection changed due to a touch/click
         * or due to focus entering the tab through navigation. Pass true
         * if it was due to a press/click and false otherwise.
         */
        public void onTabSelectionChanged(int tabIndex, boolean clicked);
    }
}

其中将OnTabSelectionChanged这个interface设置为public,

这样实现MartianTabWidget的tab点击响应事件就可以简单的调用setTabSelectionListener来实现了~


大家如有问题可留言讨论哈~

该方法已经在我们的小说阅读软件淘小说中实现,

大家多多支持哈~后续会有更多干货出来哦~




源码链接: https://pan.quark.cn/s/a4b39357ea24 Modbus协议是一种普遍应用的通信协议,在工业自动化领域具有显著地位,它为不同设备间的客户机/服务器通信确立了标准。该协议立足于OSI模型的第7层,即应用层,旨在实现通过多种总线或网络连接的设备之间的数据交换。Modbus协议主要由三个核心部分构成: 1. **Modbus协议规范**:这部分详细阐述了MODBUS事务处理机制,包括如何组织发送请求/响应报文。它定义了一组功能码,这些功能码是MODBUS协议的数据包(PDU)的组成部分,用于表明不同的服务操作。 2. **MODBUS报文传输在TCP/IP上的实现指南**:这一部分为开发者提供了在TCP/IP上实现MODBUS应用层的指导,参考了IETF的标准RFC793(TCP)RFC791(IP),以确保MODBUS报文能在网络上正确传输。 3. **MODBUS报文传输在串行链路上的实现指南**:针对使用如EIA-232EIA-485等串行通信标准的设备,提供了实现MODBUS应用层的指导,确保在串行链路上的数据完整性。 MODBUS协议支持两种通信模式: - **Modbus RTU (Remote Terminal Unit)**:适用于异步串行通信,通常用于低速、短距离通信,如EIA/TIA-232、EIA-422EIA/TIA-485。 - **Modbus TCP/IP**:基于互联网协议,使用以太网II/802.3标准,适合高速、远程通信。 在MODBUS通信栈中,MODBUS应用层位于TCP/IP之上,借助TCP的可靠连接特性,确保数据包按顺序到达。而在串行链路上,MODBUS协议则直接物理层交...
源码直接下载地址: https://pan.quark.cn/s/31ad939aed54 "关于 SR 锁存器的解析及其应用" SR 锁存器被视为一种核心的数字电子技术部件,它在数字电路构建计算机系统的开发中占据着举足轻重的地位。SR 锁存器的构造基础是两个非门,具体标识为 G1 G2。该锁存器的工作机制主要依托于 S R 两个输入端信号的逻辑关联,以此来调控输出端 Q 的状态。 SR 锁存器的工作机制可以依据输入信号的不同组合分为四种情形: 1. 在 R=0、S=0 的条件下,状态将保持恒定,即 Qn+1 等同于 Qn。 2. 当 R=0、S=1 时,执行置位操作,使得 Qn+1=1。 3. 若 R=1、S=0,则执行复位操作,导致 Qn+1=0。 4. 当 R=1、S=1 时,状态呈现不确定特性,输出端 Q 的具体状态无法预测。 SR 锁存器的实践应用极为普遍,譬如在数字电路的规划中,它能够充当 Flip-Flop 功能的载体,常见于计数器、寄存器以及计算机系统之中。此外,SR 锁存器也被广泛用于消弭由机械开关触点颤动所引发的脉冲信号输出问题。 逻辑门控 SR 锁存器可视为 SR 锁存器的一种演进形态,它通过增设使能信号 E,对 SR 锁存器的输出进行调控。逻辑门控 SR 锁存器的运作机制基于 E、S 以及 R 三个输入端信号的逻辑联系,用以控制输出端 Q 的状态。 逻辑门控 SR 锁存器的应用场景同样十分多样,例如在数字电路的设计过程中,它能够协助实现更为复杂的逻辑操作。 D 锁存器亦是一种基础性的数字电子技术器件,其运作原理 SR 锁存器相近,但 D 锁存器的输出端 Q 仅受输入信号 D 的影响。D 锁存器的实践用途同样广泛,例如在数字电路的...
源码直接下载地址: https://pan.quark.cn/s/96ee77ac4da8 根据题目指示,我们将从标题“C 语言 打印沙漏”、描述“PAT 测试题 打印沙漏 但是不知道为什么我的提交就是无效”以及部分提供的代码片段入手,对“打印沙漏”相关的基础知识进行深入剖析。 ### 一、问题背景 题目要求在 C 语言环境下开发程序,用以生成一个沙漏形态。该任务属于 PAT(Programming Ability Test)考试中的一个环节,主要评估考生对循环结构的掌握应用水平。从描述信息来看,尽管提交者已经完成了代码的编写工作,但在 PAT 平台上却显示提交无效。这或许是因为程序在逻辑上存在偏差或未能满足题目的具体规范所致。 ### 二、打印沙漏的原理 #### 1. 沙漏的基本构造 沙漏由上下两个对称部分构成。每一行均由一定数量的星号空格组成。随着行数的改变,星号的数量也会发生相应的增减变化。 #### 2. 实现过程 - **确定沙漏的规模**:首先需要明确沙漏的总行数(n),这将直接影响沙漏的最大宽度。 - **计算每一行的星号数目**:对于第 i 行(i 从 1 开始计算),其星号数目遵循公式 `2 * (n - abs(i - n)) - 1` 进行确定。 - **确定每行的空格数目**:对于第 i 行,空格数目为 `abs(n - i) - 1`。 - **输出星号空格**:依据计算出的数量,依次输出星号空格即可完成一行的打印。 #### 3. 代码范例 下面给出一个基础的 C 语言代码范例,用于生成沙漏: ```c #include <stdio.h> int main() { int n; printf("请输入沙漏的行数:"); sc...
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值