SherlockFragmentActivity抛出所需的回调异常

时间:2013-10-18 06:46:17

标签: android tabs actionbarsherlock

我是Sherlock lib的新手。我的代码如下

public class MainActivity extends SherlockFragmentActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    com.actionbarsherlock.app.ActionBar actionbar = getSupportActionBar();
    actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    actionbar.setTitle("PROFILE");
    ActionBar.Tab frag1tab = actionbar.newTab().setText("LOGIN");
    ActionBar.Tab frag2tab = actionbar.newTab().setText("REGISTER");

    Fragment fragment1 = new Fragment_1();
    Fragment fragment2 = new Fragment_2();

    frag1tab.setTabListener(new MyTabListener(fragment1));
    frag1tab.setTabListener(new MyTabListener(fragment2));

    actionbar.addTab(frag1tab);
    actionbar.addTab(frag2tab);

}

class MyTabListener implements ActionBar.TabListener {
    public Fragment fragment;

    public MyTabListener(Fragment fragment) {
        this.fragment = fragment;
    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub
        ft.replace(R.id.fragment_container, fragment);
    }

    @Override
    public void onTabSelected(Tab arg0, FragmentTransaction arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
        // TODO Auto-generated method stub

    }

}

}

我也尝试过直接实现监听器,但没有运气。它显示如下错误

java.lang.RuntimeException: Unable to start activity java.lang.IllegalStateException:     
Action Bar Tab must have a Callback

2 个答案:

答案 0 :(得分:1)

将tabListener设置为同一个标签两次,即frag1tab ..

   frag1tab.setTabListener(new MyTabListener(fragment1));
    frag1tab.setTabListener(new MyTabListener(fragment2));

应该是

   frag1tab.setTabListener(new MyTabListener(fragment1));
    frag2tab.setTabListener(new MyTabListener(fragment2));

答案 1 :(得分:0)

试试这段代码,

 @Override
    protected void onResume() {
        super.onResume();
}