I want to align the action bar title to centre without the help of custom view . I would appreciate any help.
Without using the custom view, modifying only default action bar title
You can align the title to the center when you use ActionBar
, but you can use Toolbar
to do this.
Toolbar
is more useful and easier than ActionBar
, you can use this layout to define the center title TextView
for you activity:
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="40dip">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/app_name" />
</android.support.v7.widget.Toolbar>
And use this code for a back button:
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.single_toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if(actionBar != null)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
You also need to override onCreateOptionsMenu
method for the menu, and you can refer to this project : chrisbanes/cheesesquare.