1.前提
这篇文章的前提是在MainActivity中利用FragmentTabhost维护4个标签页,每一个标签页用一个Fragment来维护。
2.问题描述
由此引发的一个问题是:如何在某一标签页中通过点击按钮,向另一标签页跳转?举例来讲,现有首页标签页HomeFragment,个人信息标签页MyInfoFragment,需求为在MyInfoFragment页面中点击“Home”按钮,返回首页HomeFragment。
3.解决思路
(1)定义标签跳转接口 TabTransferInterface,接口中定义抽象方法startFragment(“Fragment名称”)方法
(2)MainActivity实现TabTransferInterface接口,根据传入参数”Fragment名称“切换当前标签页
(3)在MyInfoFragment中定义TabTransferInterface类型的回调对象callback,为“Home按钮”添加点击监听函数,点击后回调callback的startFragment方法
4.下面引用部分代码,供读者参考
(1)TabTransferInterface
public interface TabTransferInterface {
public void startFragment(String framentName);
}
(2)MainActivity
public class MainActivity extends FragmentActivity
implements <span style="font-family: Arial, Helvetica, sans-serif;">TabTransferInterface</span>
{
private FragmentTabHost tabhost;
public static String MALL_HOME ="HomeFragment";
private void initView() {
// TODO Auto-generated method stub
tabhost = (FragmentTabHost) findViewById(android.R.id.tabhost);
tabhost.setup(this, getSupportFragmentManager(),R.id.fragmentcontent);
for(int i=0;i< textViewArray.length;i++)
{
//为每个标签设置文字、图标等
TabSpec tabSpec = tabhost.newTabSpec(textViewArray[i]).setIndicator(getTabView(i));
tabhost.addTab(tabSpec,fragmentArray[i],null);
//tabhost.getTabWidget().getChildAt(i).setBackgroundResource(resid);
}
}
@Override
public void startFragment(String str) {
// TODO Auto-generated method stub
if(str != null)
{
if(str.equals(MALL_HOME)) //根据名称跳转到home页面
{
tabhost.setCurrentTab(0);
}
}
}
//其他方法省略。。。
}
(3)MyInfoFragment
public class MyInfoFragment extends Fragment
implements View.OnClickListener
{
private View rootView;
private LinearLayout homebackLin;
private Activity mActivity;
private TabTransferInterface callback;
@Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
this.mActivity = activity;
callback = (TabTransferInterface) this.mActivity;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
if(rootView == null)
{
rootView = inflater.inflate(R.layout.*, null);
initView();
}
ViewGroup parent = (ViewGroup) rootView.getParent();
if(parent != null)
parent.removeView(rootView);
return rootView;
}
private void initView() {
// TODO Auto-generated method stub
homebackLin = (LinearLayout) rootView.findViewById(R.id.*);
addListener();
}
private void addListener() {
// TODO Auto-generated method stub
this.homebackLin.setOnClickListener(this);
}
@Override
public void onClick(View view) { //添加监听事件
// TODO Auto-generated method stub
if(view.getId() == R.id.mall_home_back)
this.callback.startFragment(MainActivity.MALL_HOME);
}
}