【问题标题】:How to navigate in fragments?如何在片段中导航?
【发布时间】:2012-04-05 08:30:30
【问题描述】:

所以我正在使用 Tabs 并寻求这种导航:

tab1 --> inside 1 --> inside2

tab2 --> inside 3 --> inside 4

tab3 --> 5内

里面我的意思是它应该打开一个新的布局和类。

我的项目主类是这样的:

public class TabsFragmentActivity extends SherlockFragmentActivity implements
        TabHost.OnTabChangeListener {

    private TabHost mTabHost;
    private HashMap<String, TabInfo> mapTabInfo = new HashMap<String, TabInfo>();
    private TabInfo mLastTab = null;
    private static Context mContext;

    private class TabInfo {
        private String tag;
        private Class clss;
        private Bundle args;
        private Fragment fragment;

        TabInfo(String tag, Class clazz, Bundle args) {
            this.tag = tag;
            this.clss = clazz;
            this.args = args;
        }
    }

    class TabFactory implements TabContentFactory {

        private final Context mContext;

        public TabFactory(Context context) {
            mContext = context;
        }

        public View createTabContent(String tag) {
            View v = new View(mContext);
            v.setMinimumWidth(0);
            v.setMinimumHeight(0);
            return v;
        }
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Step 1: Inflate layout
        setContentView(R.layout.tabs_fragment_activity);

        mContext = this;

        // Step 2: Setup TabHost
        initialiseTabHost(savedInstanceState);

        if (savedInstanceState != null) {
            mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab")); 
        }

        addNavaigationBar();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //Add Action item with title
            menu.add("some")
            .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

        return super.onCreateOptionsMenu(menu);
    }

    public void addNavaigationBar() {
        // Create Action Bar sherlock
        ActionBar navigation_bar = getSupportActionBar();

        // Setting standart navigation bar view
        navigation_bar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);

        navigation_bar.setDisplayShowTitleEnabled(true);
        navigation_bar.setTitle("Test");

        // Override Action items to navigation bar. Calls onCreateOptionsMenu
        // invalidateOptionsMenu();
    }

    protected void onSaveInstanceState(Bundle outState) {
        outState.putString("tab", mTabHost.getCurrentTabTag()); // save the tab
                                                                // selected
        super.onSaveInstanceState(outState);
    }

    /**
     * Step 2: Setup TabHost
     */
    private void initialiseTabHost(Bundle args) {
        mTabHost = (TabHost) findViewById(android.R.id.tabhost);

        mTabHost.setup();

        TabInfo tabInfo = null;

        TabsFragmentActivity.addTab(this, this.mTabHost, this.mTabHost
                .newTabSpec("Tab1").setIndicator("Tab 1"),
                (tabInfo = new TabInfo("Tab1", Tab1Fragment.class, args)));

        this.mapTabInfo.put(tabInfo.tag, tabInfo);


        TabsFragmentActivity.addTab(this, this.mTabHost, this.mTabHost
                .newTabSpec("Tab2").setIndicator("Tab 2"),
                (tabInfo = new TabInfo("Tab2", Tab2Fragment.class, args)));

        this.mapTabInfo.put(tabInfo.tag, tabInfo);

        TabsFragmentActivity.addTab(this, this.mTabHost, this.mTabHost
                .newTabSpec("Tab3").setIndicator("Tab 3"),
                (tabInfo = new TabInfo("Tab3", Tab3Fragment.class, args)));

        this.mapTabInfo.put(tabInfo.tag, tabInfo);
        // Default to first tab
        this.onTabChanged("Tab1");
        //
        mTabHost.setOnTabChangedListener(this);
    }

    private static void addTab(TabsFragmentActivity activity, TabHost tabHost,
            TabHost.TabSpec tabSpec, TabInfo tabInfo) {
        // Attach a Tab view factory to the spec
        tabSpec.setContent(activity.new TabFactory(activity));

        String tag = tabSpec.getTag();
        //getTabWidget()

        View view = prepareTabView(activity, R.id.tab_bar_icon);
        tabSpec.setIndicator(view);

        // Check to see if we already have a fragment for this tab, probably
        // from a previously saved state. If so, deactivate it, because our
        // initial state is that a tab isn't shown.
        tabInfo.fragment = activity.getSupportFragmentManager().findFragmentByTag(tag);

        if (tabInfo.fragment != null && !tabInfo.fragment.isDetached()) {

            FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction();

            ft.detach(tabInfo.fragment);

            ft.commit();

            activity.getSupportFragmentManager().executePendingTransactions();
        }
        tabHost.addTab(tabSpec);
    }

    private static View prepareTabView(Context context, int drawable){
        //inflate(R.layout.tab_indicator, android.R.id.tabs, false)
        View tabIndicator = LayoutInflater.from(context).inflate(R.layout.tab_indicator, null);
        ImageView icon = (ImageView) tabIndicator.findViewById(R.id.tab_bar_icon);
        icon.setImageResource(R.drawable.ic_launcher);
        return tabIndicator;

    }

    public void onTabChanged(String tag) {
        TabInfo newTab = this.mapTabInfo.get(tag);

        if (mLastTab != newTab) {
            FragmentTransaction ft = this.getSupportFragmentManager()
                    .beginTransaction();
            if (mLastTab != null) {
                if (mLastTab.fragment != null) {
                    ft.detach(mLastTab.fragment);
                }
            }
            if (newTab != null) {
                if (newTab.fragment == null) {
                    newTab.fragment = Fragment.instantiate(this,
                            newTab.clss.getName(), newTab.args);
                    ft.add(R.id.realtabcontent, newTab.fragment, newTab.tag);
                } else {
                    ft.attach(newTab.fragment);
                }
            }

            mLastTab = newTab;
            ft.commit();
            this.getSupportFragmentManager().executePendingTransactions();
        }
    }

}

这将创建 3 个包含内容的选项卡。下面是 Tab1 片段类的样子(其他看起来类似):

public class Tab1Fragment extends SherlockFragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        if (container == null) {
            // We have different layouts, and in one of them this
            // fragment's containing frame doesn't exist.  The fragment
            // may still be created from its saved state, but there is
            // no reason to try to create its view hierarchy because it
            // won't be displayed.  Note this is not needed -- we could
            // just run the code below, where we would create and return
            // the view hierarchy; it would just never be used.
            return null;
        }
        LinearLayout theLayout = (LinearLayout)inflater.inflate(R.layout.tab_frag1_layout, container, false);
        // Register for the Button.OnClick event
        Button b = (Button)theLayout.findViewById(R.id.frag1_button);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

**//Here i want open a new window but don't change pressed tab and when press back it should go back at this window**
            }
        });
        return theLayout;
    }
}

我在按钮上写下我想要的。

我无法在此片段中打开新片段或活动?

我应该如何在片段中导航?

【问题讨论】:

    标签: android android-fragments actionbarsherlock


    【解决方案1】:

    我喜欢让我的主机Activity 处理所有转换,所以我在片段中所做的是创建一个interface 来处理导航。例如,您可以将此interface 添加到您的Tab1Fragment

    public interface Callback {
        public void onButtonBClicked();
    }
    

    然后在您的TabsFragmentActivity 中实现Tab1Fragment.Callback,这将要求您实现onButtonBClicked()。以下是如何实现此方法的示例:

    @Override
    public void onButtonBClicked() {
    
        Fragment anotherFragment = Fragment.instantiate(this, AnotherFragment.class.getName());
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.add(R.id.realtabcontent, anotherFragment);
        ft.addToBackStack(null);
        ft.commit();
    }
    

    快完成了。接下来,您需要做的是在片段中获取对此回调的引用。这通常在onAttached() 方法中实现。例如:

    @Override
    public void onAttach(Activity activity) {
    
        super.onAttach(activity);
        try {
            mCallback = (Callback) activity;
        }
        catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement " + Callback.class.getName());
        }
    }
    

    最后,在您的OnClickListener 中,致电mCallback.onButtonBClicked()

    【讨论】:

    • 这是使用回调的好例子。但是如果我在我的 Fragment1 OnClickListiner 中调用这个有什么区别: ((TabsFragmentActivity) getActivity()).onButtonBClicked();这也将调用 onButtonBClicked()。但是如何处理每个选项卡的堆栈呢?
    • 它没有什么区别,只是我这样做的方式更干净,因为您只需投射一次(如果您有一个更强大的接口,可以进行多次调用)。我对onButtonClicked() 的实现将片段添加到后堆栈,因此按下返回将显示前一个片段。
    • 好的,那么如何切换标签?我的意思是我将 tab1 放入深层堆栈,然后切换到 tab2 并进入深层,然后再次切换到 tab1 并按返回按钮,我希望它会返回到 tab1
    • 啊,我明白了。所以你希望每个选项卡都有自己独立的回栈,而在切换选项卡时,你“切换”回栈?
    • 是的,我正在为此寻求解决方案
    猜你喜欢
    • 1970-01-01
    • 2019-09-19
    • 2015-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多