6

目前,我使用 ABS、ActionBar 选项卡和 TabsAdapter/ViewPager 为我的应用程序制作一个不错的选项卡布局。我有 5 个以上的类别选项卡 - 最终用户也可以添加新类别(我稍后会设置)。所以,目前,我有一个SherlockFragmentActivity包含许多SherlockFragment类别文件的主目录。在主 SFA 的 onCreate 中,我构建了 actionBar 并添加了它的所有选项卡,如下所示:

mTabsAdapter.addTab(bar.newTab().setText(R.string.login),
            LoginFragment.class, null);
    mTabsAdapter.addTab(bar.newTab().setText("Geographics"),
            GeoFragment.class, null);
    mTabsAdapter.addTab(bar.newTab().setText(R.string.economics),
            EconFragment.class, null);
    mTabsAdapter.addTab(bar.newTab().setText(R.string.elections),
            ElectionsFragment.class, null);

相反,我想做的是创建一个新的解决方案,CategoryFragment而不是使用所有特定的选举、地理、经济等。谁能想象一个解决方案?理想情况下,我只想将一个字符串传递给添加的选项卡,以便 CategoryFragment 可以根据该字符串膨胀。我想要这个解决方案,因为代码在多个类中非常冗余,当所有类真正做的是从 SQL dB 在线加载东西时,只获取其自己类别的数据。

这是我的 TabsAdapter 类:

public class TabsAdapter extends FragmentPagerAdapter
implements ActionBar.TabListener, ViewPager.OnPageChangeListener {
    private final Context mContext;
    private Polling activity;
    private final ActionBar mActionBar;
    private final ViewPager mViewPager;
    private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

    final class TabInfo {
        private final Class<?> clss;
        private final Bundle args;
        //private final String title;
                    //This string is implemented only as part of my attempt!

        TabInfo(Class<?> _class, Bundle _args, String _title) {
            clss = _class;
            args = _args;
            title = _title;
        }
    }
    /*Constructor method that adds a TabsAdapter to each tab that is created.
     * It also adds the ViewPager to each tab so that the user can swipe to change tabs.
     */
    public TabsAdapter(SherlockFragmentActivity activity, ViewPager pager) {
        super(activity.getSupportFragmentManager());
        mContext = activity;
        this.activity = (Polling) activity;
        mActionBar = activity.getSupportActionBar();
        mViewPager = pager;
        mViewPager.setAdapter(this);
        mViewPager.setOnPageChangeListener(this);
    }

    /*This is the method I've been trying to use to solve the problem, but it's not really cutting it!*/

    public void buildTabs() throws ClassNotFoundException { 
        String [] tabs = {"Econ", "Elections", "Geo", "Politics", "Science", "Finance", "Religion", 
                "Military", "International" };
        final String resource = "R.string.";            
        mTabsAdapter.addTab(bar.newTab().setText("Login"),
                LoginFragment.class, null, "Login");
        for (int j = 0; j < tabs.length; j++) {
            String res = resource + tabs[j];
            String clas = tabs[j] + "Fragment";
            String total = "com.davekelley.polling." + clas;
        mTabsAdapter.addTab(bar.newTab().setText(tabs[j]),
                CategoryFragment.class, null, tabs[j]);
        }           
    }

    /*A fairly simple method that sets the TabInfo for each tab so that the TabsAdapter
     * knows which class the tab that is being added actually belonds to. It also updates
     * the UI interface when each tab is added. 
     */

    public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args, String title) {
        TabInfo info = new TabInfo(clss, args, title);
        tab.setTag(info);
        tab.setTabListener(this);
        mTabs.add(info);
        mActionBar.addTab(tab);
        notifyDataSetChanged();
    }   

    public int getCount() {
        return mTabs.size();
    }
    /*A method that is used in other classes to allow each tab Fragment to 
     * access its inherited methods from a mother-class, in this case, SherlockFragment
     */

    public int getPosition(SherlockFragment fragment) {
        for (int j = 1; j < mTabs.size(); j++) {
            TabInfo info = (TabInfo) mActionBar.getTabAt(j).getTag();
            if (info.title.matches(mTabs.get(j).title)) {
                return j;
            }
        }
        return -1;


    }
    public SherlockFragment getItem(int position) {
        TabInfo info = mTabs.get(position);
        return (SherlockFragment)Fragment.instantiate(mContext, info.clss.getName(), info.args);
    }
    /*This method reads the user's selection for a new tab and sets that tab as
     * the new current focus.*/
    public void onPageSelected(int position) {
        mActionBar.setSelectedNavigationItem(position);
        selectInSpinnerIfPresent(position, true);
    }

    private void selectInSpinnerIfPresent(int position, boolean animate) {
        try {
            View actionBarView = findViewById(R.id.abs__action_bar);
            if (actionBarView == null) {
                int id = getResources().getIdentifier("action_bar", "id", "android");
                actionBarView = findViewById(id);
            }

            Class<?> actionBarViewClass = actionBarView.getClass();
            Field mTabScrollViewField = actionBarViewClass.getDeclaredField("mTabScrollView");
            mTabScrollViewField.setAccessible(true);

            Object mTabScrollView = mTabScrollViewField.get(actionBarView);
            if (mTabScrollView == null) {
                return;
            }

            Field mTabSpinnerField = mTabScrollView.getClass().getDeclaredField("mTabSpinner");
            mTabSpinnerField.setAccessible(true);

            Object mTabSpinner = mTabSpinnerField.get(mTabScrollView);
            if (mTabSpinner == null) {
                return;
            }

            Method setSelectionMethod = mTabSpinner.getClass().getSuperclass().getDeclaredMethod("setSelection", Integer.TYPE, Boolean.TYPE);
            setSelectionMethod.invoke(mTabSpinner, position, animate);

        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public void onPageScrollStateChanged(int state) {}
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
    /* This is the method that actually draws the newest tab onto the screen when
     * it is selected.*/
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        mViewPager.setCurrentItem(tab.getPosition());

        sp = getSharedPreferences("prefs", MODE_PRIVATE);
        SharedPreferences.Editor preferencesEditor = sp.edit();
        preferencesEditor.putInt("lastPosition", mViewPager.getCurrentItem());
        preferencesEditor.commit();
    }
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {}
    public void onTabReselected(Tab tab, FragmentTransaction ft) {}
    public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {}
    public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {}
}
4

2 回答 2

1

好吧,你想使用一个 Fragment 类,比如BaseFragment,而不是多个类;通过为这个新片段传递一个字符串(标识符)来做到这一点。您还可以在所有这些片段中运行一些代码,因此最好使用新方法。

但是,将标识符传递给此BaseFragment只会导致其代码混乱,您将不得不处理所有这些if...else,当它确实与此标识符相关并且您的代码实际上仍然相同,因为您必须移动代码将特定片段放入此 BaseFragment 中。因此,这种方法没有附加价值。您可以保留所有片段,并在添加选项卡时实际使用此“标识符”来选择要添加的正确片段。


至于在您的许多片段中运行的代码。这是一个非常基本的方法:

创建一个扩展 Fragment 的类 BaseFragment。(我在这里很天真)添加一个common()可以做这个常见事情的函数。最后让你所有的 Fragment 扩展这个 BaseFragment 而不是 Fragment。现在,您可以调用common(). (同样,您可能需要common1(), common2(),...)。

于 2012-12-28T11:05:13.880 回答
1

对于您的课程,您需要使用反射;仅有字符串名称是不够的;所以可能你将不得不写类似的东西:

String clas = tabs[j] + "Fragment";
String total = "com.davekelley.polling." + clas;
Class<?> theClass = Class.forName (total);

对于资源,您不能简单地编写类似的东西String res = "R.string" + tabs[j];,您需要使用函数getIdentifier();有关示例,请参见动态资源加载 Android 。

于 2012-12-28T14:01:34.537 回答