如何从活动中分段

sar*_*abu 6 android android-fragments android-activity actionbarsherlock

我正在使用ActionBarSherlock,我无法前往延伸SherlockFragment活动的课程

我需要从Activity转移到片段类

这是我的Activity类

Intent notificationIntent = new Intent(context,MessagesFragment.class);
Run Code Online (Sandbox Code Playgroud)

Fragment类就像

public class MessagesFragment extends SherlockFragment implements
    OnItemClickListener {

// Layout parameters declaration
private PullToRefreshListView lv_messages;
private ImageView iv_no_data;
private LinearLayout ll_bg;

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    getSherlockActivity().getSupportActionBar().setDisplayOptions(
            ActionBar.DISPLAY_SHOW_CUSTOM);
    getSherlockActivity().getSupportActionBar().setDisplayHomeAsUpEnabled(
            true);
    getSherlockActivity().getSupportActionBar().setHomeButtonEnabled(true);
    getSherlockActivity().getSupportActionBar().setDisplayShowHomeEnabled(
            true);
    getSherlockActivity().getSupportActionBar().setCustomView(
            R.layout.header);
    getSherlockActivity().getSupportActionBar().setBackgroundDrawable(
            new ColorDrawable(Color.parseColor("#009fe3")));
    TextView txt = (TextView) getActivity().findViewById(
            R.id.tv_title_header);
    Typeface font = Typeface.createFromAsset(getActivity().getAssets(),
            "georgia.ttf");
    txt.setText("MESSAGES");
    txt.setTypeface(font);
    return inflater.inflate(R.layout.listview_refreshable, null);
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}
.
.
.
.
}
Run Code Online (Sandbox Code Playgroud)

如果我使用switchfragment方法,它会显示很多错误FragmentChangeActivity

private void switchFragment(Fragment fragment) {
    if (getActivity() == null)
        return;

    if (getActivity() instanceof FragmentChangeActivity) {
        FragmentChangeActivity fca = (FragmentChangeActivity) getActivity();
        fca.switchContent(fragment);

    }
}
Run Code Online (Sandbox Code Playgroud)

cod*_*441 12

您需要创建一个扩展FragmentActivity的类并在那里开始您的片段

public class MessagesFragmentActivity extends SherlockFragmentActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null){
            getSupportFragmentManager().beginTransaction()
                    .add(android.R.id.content, new MessagesFragment ()).commit();}
    }
}
Run Code Online (Sandbox Code Playgroud)

你的片段构造函数.

public YourFragment() {
}
Run Code Online (Sandbox Code Playgroud)

然后从你调用活动,以正常方式开始你的片段活动

Intent i = new Intent(YourActivity.this,MessagesFragment.class);
startActivity(i);
Run Code Online (Sandbox Code Playgroud)