Как выровнять название в центре ActionBar в теме по умолчанию (Theme.Holo.Light)
Я много искал, но не могу найти способ. Как установить заголовок в центре ActionBar вместо выравнивания по левому краю. Я использовал ниже код, чтобы установить название в центре:
ViewGroup decorView= (ViewGroup) this.getWindow().getDecorView();
LinearLayout root= (LinearLayout) decorView.getChildAt(0);
FrameLayout titleContainer= (FrameLayout) root.getChildAt(0);
TextView title= (TextView) titleContainer.getChildAt(0);
title.setGravity(Gravity.CENTER);
Но это дает ошибку, как показано ниже:
ClassCastException : com.android.internal.widget.ActionBarView can not
be cast to android.widget.TextView.
Любое другое решение. Любая помощь будет оценена.
Ответы
Ответ 1
Вы можете создать собственный макет и применить его к actionBar.
Чтобы сделать это, выполните следующие два простых шага:
Где R.layout.actionbar
- следующий макет.
-
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="@+id/action_bar_title"
android:text="YOUR ACTIVITY TITLE"
android:textColor="#ffffff"
android:textSize="24sp" />
</LinearLayout>
Это может быть так сложно, как вы хотите. Попробуйте!
EDIT:
Чтобы установить background
, вы можете использовать свойство android:background
в макете контейнера (LinearLayout в этом случае). Возможно, вам потребуется установить высоту макета android:layout_height
на match_parent
вместо wrap_content
.
Кроме того, вы можете добавить в него ЛОГО/ ICON. Для этого просто добавьте ImageView внутри вашего макета и задайте свойство ориентации ориентации android:orientation
горизонтально (или просто используйте RelativeLayout и управляйте им самостоятельно).
Чтобы изменить название выше настраиваемой панели действий динамически, сделайте следующее:
TextView title=(TextView)findViewById(getResources().getIdentifier("action_bar_title", "id", getPackageName()));
title.setText("Your Text Here");
Ответ 2
Кажется, нет никакого способа сделать это без специального представления. Вы можете получить название:
View decor = getWindow().getDecorView();
TextView title = (TextView) decor.findViewById(getResources().getIdentifier("action_bar_title", "id", "android"));
Но изменение gravity
или layout_gravity
не влияет.
Проблема в ActionBarView
, которая сама компонует свои дети, поэтому изменение параметров макета его детей также не имеет эффекта.
Чтобы увидеть это, выполните следующий код:
ViewGroup actionBar = (ViewGroup) decor.findViewById(getResources().getIdentifier("action_bar", "id", "android"));
View v = actionBar.getChildAt(0);
ActionBar.LayoutParams p = new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
p.gravity= Gravity.CENTER;
v.setLayoutParams(p);
v.setBackgroundColor(Color.BLACK);
Ответ 3
Откройте новую панель инструментов в классе библиотеки поддержки в обновлении Lollipop, вы можете создать панель действий, добавив панель инструментов в макет.
добавьте эти элементы в тему приложения
<item name="android:windowNoTitle">true</item>
<item name="windowActionBar">false</item>
Создайте свою панель инструментов в макете и включите текст в центр дизайна вашей панели инструментов
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/acbarcolor">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/app_name"
android:textColor="#ffffff"
android:textStyle="bold" />
</RelativeLayout>
</android.support.v7.widget.Toolbar>
добавить панель действий в качестве панели инструментов
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
убедитесь, что вам нужно включить панель инструментов в файл ресурса, подобный этому
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:orientation="vertical"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<include
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="@layout/toolbar" />
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="@+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:layout_width="match_parent"
android:layout_height="match_parent"
layout="@layout/homepageinc" />
</FrameLayout>
<fragment
android:id="@+id/fragment1"
android:layout_gravity="start"
android:name="com.shouldeye.homepages.HomeFragment"
android:layout_width="250dp"
android:layout_height="match_parent" />
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
Ответ 4
Это действительно работает:
getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getActionBar().setCustomView(R.layout.custom_actionbar);
ActionBar.LayoutParams p = new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
p.gravity = Gravity.CENTER;
Вам нужно определить макет custom_actionbar.xml, который соответствует вашему требованию, например.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#2e2e2e"
android:orientation="vertical"
android:gravity="center"
android:layout_gravity="center">
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/top_banner"
android:layout_gravity="center"
/>
</LinearLayout>
Ответ 5
Я знаю, что мой ответ не вовремя, но это чистый код xml
.
Это для использования в Activity
public void setTitle(String title){
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
TextView textView = new TextView(this);
textView.setText(title);
textView.setTextSize(20);
textView.setTypeface(null, Typeface.BOLD);
textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
textView.setGravity(Gravity.CENTER);
textView.setTextColor(getResources().getColor(R.color.white));
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(textView);
}
Это используется для Fragment
public void setTitle(String title){
((AppCompatActivity)getActivity()).getSupportActionBar().setHomeButtonEnabled(true);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
TextView textView = new TextView(getActivity());
textView.setText(title);
textView.setTextSize(20);
textView.setTypeface(null, Typeface.BOLD);
textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
textView.setGravity(Gravity.CENTER);
textView.setTextColor(getResources().getColor(R.color.white));
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
((AppCompatActivity)getActivity()).getSupportActionBar().setCustomView(textView);
}
Ответ 6
Я думаю, позиционируя представления на панели действий, вы достигнете того, что хотите. На макете панели действий, когда параметры макета установлены в соответствии с родительским, он не соответствует полной ширине
поэтому я сделал это программно там, где мне удалось. Ширина установки (она работает как layout_weight = "value" ), мы можем установить наш вид везде, где захотим:
actionBar = getSupportActionBar();
actionBar.setDisplayShowCustomEnabled(true);
LayoutInflater ll = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout linearLayout = (LinearLayout) ll.inflate(R.layout.custom_actionbar, null);
//inner layout within above linear layout
LinearLayout inner = (LinearLayout) linearLayout.findViewById(R.id.inner_linear_ractionbar);
inner.setMinimumWidth(getWidth() * 2 / 10);
// we will set our textview to center and display there some text
TextView t = (TextView) linearLayout.findViewById(R.id.center_text);
t.setWidth(getWidth() * 6 / 10);
Button b = (Button) linearLayout.findViewById(R.id.edit_button);
b.setWidth(getWidth() *3/ 20);
ImageButton imageButton = (ImageButton) linearLayout.findViewById(R.id.action_bar_delete_item);
imageButton.setMinimumWidth(deviceUtils.getWidth() / 20);
и вот метод getWidth():
public int getWidth() {
DisplayMetrics dm = new DisplayMetrics();
mActivity.getWindowManager().getDefaultDisplay().getMetrics(dm);
return dm.widthPixels;
}
Ответ 7
Код Java:
напишите это в onCreate()
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setCustomView(R.layout.action_bar);
и для вас пользовательский вид, просто используйте FrameLayout, восточный peasy!
android.support.v7.widget.Toolbar - еще один вариант
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="@string/app_name"
android:textColor="@color/black"
android:id="@+id/textView" />
</FrameLayout>
Ответ 8
У меня была та же проблема, и из-за кнопки "Главная", добавленной автоматически на панели инструментов, мой текст не был точно введен.
Я исправил это грязным способом, но он хорошо работает в моем случае. Я просто добавил поле справа от своего TextView, чтобы компенсировать кнопку home слева. Здесь мой макет панели инструментов:
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:elevation="1dp"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
android:gravity="center"
android:background="@color/mainBackgroundColor"
android:fitsSystemWindows="true" >
<com.lunabee.common.utils.LunabeeShadowTextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="?attr/actionBarSize"
android:gravity="center"
style="@style/navigation.toolbar.title" />
</android.support.v7.widget.Toolbar>
Ответ 9
Вы можете заставить панель инструментов обернуть заголовок заголовка и уровня справа, который по умолчанию оставил дополнение для заголовка. Чем цвет фона для родителя панели инструментов, и та часть, которая вырезана с помощью заголовка, имеет один и тот же цвет (белый в моем примере):
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/white">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="wrap_content"
android:layout_height="56dp"
android:layout_gravity="center_horizontal"
android:paddingEnd="15dp"
android:paddingRight="15dp"
android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
app:titleTextColor="@color/black"/>
</android.support.design.widget.AppBarLayout>