我正在创建自定义actionBar。一切正常,但我没有将文本放在actionBar的中心。搜索互联网的解决方案有很多,但对我来说没有。任何人都可以帮助我实现它。我试图实现以下问题的答案但它也没有效果。How to center align the ActionBar title in Android?
虽然我可以通过填充textview将文本置于中心,但我认为这不是正确的方法。
以下是代码:
自定义ActionBar代码:
private void createCustomActionBarTitle()
{
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#8B58A3")));
LayoutInflater inflater = LayoutInflater.from(this);
View v = inflater.inflate(R.layout.titleview, null);
TextView frag1 = (TextView)v.findViewById(R.id.titleFragment1);
frag1.setTypeface(vivaldiiFont);
actionBar.setCustomView(v);
}
和xml代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/actionBar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:paddingTop="7dp"
android:orientation="horizontal">
<TextView
android:id="@+id/titleFragment1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/Title"
android:textSize="20sp"
android:textColor="#FFFFFF"
android:layout_gravity="center" />
这就是actionBar现在的方式
此文本应位于中心而不是左侧。
答案 0 :(得分:1)
试试这个......
<强> 1。 custom_action_bar.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:layout_gravity="center"
android:background="@android:color/holo_blue_light" >
<TextView
android:id="@+id/apptitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_gravity="center_horizontal|center_vertical"
android:gravity="center_horizontal|center_vertical"
android:padding="8dp"
android:text="@string/app_name"
android:textColor="#FFFFFF"
android:textSize="16sp" />
</RelativeLayout>
答案 1 :(得分:0)
<?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="match_parent"
android:orientation="horizontal"
android:background="@drawable/header" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:id="@+id/mytext"
android:textColor="@color/header_text_color"
android:textSize="18sp"
android:textStyle="bold"/>
</RelativeLayout>
这样做你会得到你想要的。