[英]How to change the selected tab on button click?
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。
adding these two lines did the trick inside of my button handler: 添加这两行在我的按钮处理程序中成功了:
ActionBar actionBar = (ActionBar)getActivity().getActionBar();
actionBar.setSelectedNavigationItem(1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.