Matej Procházka Matej Procházka - 1 month ago 17
Android Question

Center TextView in custom ActionBar horizontally

A want to create custom ActionBar with app name in center of it but it is still aligned to left. Here is xml of custom_actionbar.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:background="@color/transparent">

<TextView
android:id="@+id/nav_bar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="@color/transparent"
android:singleLine="true"
android:textColor="@color/sue_green"
android:text="@string/app_name"
android:textAppearance="?android:attr/textAppearanceLarge">
</TextView>

</RelativeLayout>


Here is on create of Activity:

public class DeviceOverviewActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);

setTheme(R.style.Theme_SUE);
setContentView(R.layout.activity_device_overview);

final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayUseLogoEnabled(false);

LayoutInflater inflator = (LayoutInflater) this .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflator.inflate(R.layout.custom_actionbar, null);

actionBar.setDisplayShowCustomEnabled(true);
actionBar.setCustomView(v);
}
...
}


Can you advice what am I doing wrong?
Thanks

Answer

Change the TextViews width to match_parent and apply a android:gravity="center_horizontal"