从Fragment To Activity返回Action Bar

时间:2015-03-25 11:27:37

标签: android android-fragments android-activity android-actionbar

我想在操作栏上放一个按钮然后点击后我想回到一个活动。我正在编写以下代码,但我无法实现相同的目标。请帮我。 Thnks

   public class NutrientDailyTrackerActivity extends Fragment {



 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    rootView = inflater.inflate(R.layout.activity_nutrient_details, container, false);  
    ActionBar actionBar = getActivity().getActionBar();

    actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#4CC1D2")));
    actionBar.setTitle("Nutrient Tracker");
    actionBar.setDisplayHomeAsUpEnabled(true);
                 // doing some task here

    }



@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        // app icon in action bar clicked; go home
        Intent intent = new Intent(getActivity(), CalorieMainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        return true;
    default:
        return super.onOptionsItemSelected(item);

    }
}

}

1 个答案:

答案 0 :(得分:2)

片段托管在Activity内。而且ActionBar也托管在Activity中。因此,您应该在托管Activity的{​​{1}}内写下此内容。

ActionBar的代码放在托管片段的Actionbar onCreate内。并且不要忘记将后退按钮点击处理程序的代码移动到Activity