0

對於特定設計,我希望工具欄標題文本居中。如何在Android中的FRAGMENT中標題標題工具欄?

我沒有通過以下instructions,我創建2個textviews的自定義工具欄小工具能夠得到它從一個片段內工作,雖然 我已成功地做到這一點在活動工具欄,並將其設置爲SupportActionBar,將該工具欄的xml添加爲活動的佈局xml中的include。這樣的事情:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarCouponDetailed); 
    setSupportActionBar(toolbar); 
    getSupportActionBar().setDisplayShowTitleEnabled(false); 
    getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
    getSupportActionBar().setDisplayShowHomeEnabled(true); 
    getSupportActionBar().setDisplayShowCustomEnabled(true); 

    TextView toolbarTitle = (TextView) findViewById(R.id.toolbar_coupons_title); 
    TextView toolbarTitleDate = (TextView) findViewById(R.id.toolbar_coupons_title_date_text); 
    toolbarTitle.setText(StringUtils.onlyFirstLetterUpperCase(mCoupon.getRetailerName())); 
    toolbarTitleDate.setText(mCoupon.getDateTxt()); 

    toolbar.setNavigationOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      onBackPressed(); 
     } 
    }); 

我試圖使用相同的方法,但不知何故,我似乎可以得到它的工作。 有沒有人有一個想法或代碼示例解決這個問題?

編輯: 我實際上已經爲我包含在片段xml中的片段創建了另一個工具欄佈局。在onCreateView()我創建了一個成員變量創建到工具欄上的參考,我則可以使用onActivityCreated(),我稱之爲:

((MainActivity) getActivity()).setSupportActionBar(mToolbar); 
    ((MainActivity) getActivity()).getSupportActionBar().setDisplayShowCustomEnabled(true); 
    ((MainActivity) getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false); 

但活動的工具欄仍然採用這種方式

+0

[Android的工具欄標題中心和自定義字體(HTTP的可能重複調用方法://計算器.com/questions/26533510/android-toolbar-center-title-and-custom-font) – Emil

+0

@Boss:是的,我也讀過這篇文章,但正如我所解釋的,我設法解決了在工具欄中居中標題的問題活動,但我的問題在這裏涉及從一個片段集中工具欄的標題 –

+0

只需使用另一個工具欄佈局僅用於該片段 - 會爲你工作? – yennsarah

回答

0

不需要爲fragment創建另一個toolbar,因爲工具欄是Actvity的一部分,也是片段。只有一個工具欄應該是有

使用以下方法,在每一個fragment或創建BaseFragmentonCreate()

protected void setTitleFragment(String strTitle){ 
    Toolbar mToolbar = (Toolbar) ((AppCompatActivity)getActivity()).findViewById(R.id.toolbar); 
    TextView txtTitle =((TextView)mToolbar.findViewById(R.id.toolbar_title)); 
    txtTitle.setText(strTitle); 
}