如何更改按钮单击时选定的选项卡?

时间:2022-08-23 22:40:36

I have followed the tutorial found here:

我按照这里的教程:

Implementing Fragment Tabs in Android

在Android中实现片段选项卡

and I have it working properly, but I wanted to be able to switch the fragments on button click, not just on tab selection. So inside of FragmentTab1() I have added an ImageButton that lets me switch out my fragments, and open FragmentTab2().

我让它正常工作,但我希望能够在按钮点击时切换片段,而不仅仅是在标签选择上。因此,在FragmentTab1()内部,我添加了一个ImageButton,可以让我切换出我的片段,然后打开FragmentTab2()。

This is the code inside of FragmentTab1() in OnCreateView():

这是OnCreateView()中FragmentTab1()内部的代码:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_form1, container, false);
    btnFragment1 = (ImageButton) rootView.findViewById(R.id.next);

    btnFragment1.setOnClickListener(btnFragmentOnClickListener);

    return rootView;
}

This is the code for my button:

这是我按钮的代码:

Button.OnClickListener btnFragmentOnClickListener
        = new Button.OnClickListener(){

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Fragment newFragment;

        newFragment = new FragmentTab2();

        // Create new transaction
        FragmentTransaction transaction = getFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack
        transaction.replace(R.id.fragment_container, newFragment);
        transaction.addToBackStack(null);

        // Commit the transaction
        transaction.commit();
    }};
}

This works properly to switch out the fragments.

这适用于切换片段。

My question is: How do I get the selected tab to have the blue line underneath the text in the tab itself? Any help would be appreciated!

我的问题是:如何让选定的选项卡在选项卡本身的文本下方显示蓝线?任何帮助,将不胜感激!

Edit: I am not using a TabHost so this makes the solution trickier, I am using ActionBar.TabListener.

编辑:我没有使用TabHost所以这使解决方案更棘手,我正在使用ActionBar.TabListener。

1 个解决方案

#1


adding these two lines did the trick inside of my button handler:

添加这两行是我的按钮处理程序中的技巧:

ActionBar actionBar = (ActionBar)getActivity().getActionBar();
actionBar.setSelectedNavigationItem(1);

#1


adding these two lines did the trick inside of my button handler:

添加这两行是我的按钮处理程序中的技巧:

ActionBar actionBar = (ActionBar)getActivity().getActionBar();
actionBar.setSelectedNavigationItem(1);