2012-10-28 26 views
4

我想添加一個ActionBar到我的Fragment類,但我不斷收到錯誤。這是我的課:getActionBar()未定義

public class TaskDetailFragment extends Fragment { 

    public static final String ARG_ITEM_ID = "item_id"; 

    MyTasks.taskItem mItem; 

    public TaskDetailFragment() { 

    } 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     if (getArguments().containsKey(ARG_ITEM_ID)) { 
      mItem = MyTasks.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID)); 
     } 
    } 


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

     View rootView = inflater.inflate(R.layout.fragment_task_detail, 
       container, false); 

     ActionBar actionBar = getActionBar(); 
     actionBar.show(); 


     if (mItem != null) { 
      //Add TexViews 
      ((TextView) rootView.findViewById(R.id.in_Name)) 
        .setText(MyTasks.customers[(Integer.parseInt(mItem.id))][1]); 
      ((TextView) rootView.findViewById(R.id.in_Address)) 
        .setText(MyTasks.customers[(Integer.parseInt(mItem.id))][3] + " " + MyTasks.customers[(Integer.parseInt(mItem.id))][2]); 

     } 
     return rootView; 
    } 
} 

這是我的錯誤:

The method getActionBar() is undefined for the type TaskDetailFragment

回答

12

據我所知,你需要問的Activity(這是該Fragment已附後)爲ActionBar

ActionBar actionBar = getActivity().getActionBar(); 

或者,如果您使用的支持庫和/或ActionBarSherlock:

ActionBar actionBar = getFragmentActivity().getSupportActionBar(); 

片段沒有定義getActionBar()方法,因此是錯誤消息。

0

確保getActionBar()在TaskDetailFragment或其他超或有時機器人emulataor定義可以加上「保護」的定義的方法

0

如果一個片段想要使用ActionBar,它必須調用setHasOptionsMenu(true),通常從onCreate()

+0

如果我調用setHasOptionsMenu(true),我仍然得到相同的錯誤。 – ObAt