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); 
}