2015-03-19 107 views
2

我有一個片段,其中啓用了操作欄後退按鈕。操作欄檢測後退按鈕單擊片段

代碼:

@Override 
    public void onAttach(Activity activity) { 
     super.onAttach(activity); 
     setHasOptionsMenu(true); 
     actionBar = ((MainActivity)getActivity()).getSupportActionBar(); 
     actionBar.setDisplayHomeAsUpEnabled(true); 

     actionBar.setCustomView(R.layout.custom_action_bar); 
     actionBar.setDisplayShowTitleEnabled(false); 
     actionBar.setDisplayShowCustomEnabled(true); 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     mInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     View view = mInflater.inflate(R.layout.fragment_layout, container, false); 

     return view; 
    } 

在上面的代碼actionBar.setDisplayHomeAsUpEnabled(true);使操作欄後退按鈕,但我們如何可以檢測它的點擊?

我已經調查的例子很多,並試圖以下,但仍然沒有工作:

在片段:

@Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     switch (item.getItemId()) { 
     case android.R.id.home: 
      Toast.makeText(getActivity(), "Back", Toast.LENGTH_LONG).show(); 
      break; 
     default: 
      break; 
     } 
     return super.onOptionsItemSelected(item); 
    } 

而且其顯示在片段中的後退按鈕是黑顏色的,我需要的是在白色或自定義顏色我怎麼能改變這一點?

+0

onOptionSelectde(MenuItem項)是甚至菜單項,並與actionBar.setDisplayHomeAsUpEnabled(true),它會自動返回設施..不經過其點擊事件.... – Vidhi 2015-03-19 06:49:07

+0

@VidhiTrivedi當我點擊它,它什麼也沒做,那麼我的下一步是檢查我做錯了什麼? – user2056563 2015-03-19 06:52:00

+0

我也面臨同樣的問題任何人找到解決這個?無法檢測到android.R.id.home事件 – Swapnil 2015-06-10 08:00:32

回答

0
View cView = getLayoutInflater().inflate(R.layout.header, null); 
cView.findViewById(R.id.btn_id).setOnClickListener(new OnClickListener() { 
    @Override 
    public void onClick(View v) { 
        // Do stuff here. 
    } 
}); 
actionBar.setCustomView(cView); 
2

我面臨同樣的問題,但後來我把這個代碼的活動中和後退按鈕從片段內的工作:

@Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     switch (item.getItemId()) { 
     case android.R.id.home: 
      Toast.makeText(getActivity(), "Back", Toast.LENGTH_LONG).show(); 
      break; 
     default: 
      break; 
     } 
     return super.onOptionsItemSelected(item); 
    } 
1

優於從不遲到,請試試這個>

@Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     mInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     View view = mInflater.inflate(R.layout.fragment_layout, container, false); 
     //set setHasOptionsMenu on true here on CreateView method 
     setHasOptionsMenu(true); 
     return view; 
    } 

和實施

@Override 
public boolean onOptionsItemSelected(MenuItem item){ 
      if (item.getItemId() == android.R.id.home) { 
       if (getActivity() != null) { 
        getActivity().onBackPressed(); 
       } 
       return true; 
      }; 
      return super.onOptionsItemSelected(item); 
}