2015-08-25 3 views
2

У меня есть обычай toolbar, и я использую TextSwitcher. Моя проблема в том, что я сосредоточен на тексте, но когда я применяю кнопку «Назад», текст перемещается вправо. Я предполагаю, что это вызвано кнопкой, создающей собственный макет, перемещающий существующий. Я заметил, что текст снова центрируется, если включить параметры на toolbar, но я не хочу этого. Я попытался настроить видимость параметров на скрытые, но, похоже, полностью удалит элемент. Я бы предпочел не создавать пользовательскую кнопку «назад», поэтому любая помощь была бы оценена. Следующий код в моем onCreate метод в моем Activity:Центрирующая панель инструментов Название

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    TextSwitcher tvToolbar = (TextSwitcher) findViewById(R.id.textSwitcher); 
    tvToolbar.setFactory(new ViewSwitcher.ViewFactory() { 

     public View makeView() { 
      TextView myText = new TextView(MyActivity.this); 
      myText.setGravity(Gravity.CENTER); 
      myText.setSingleLine(true); 
      myText.setTextSize(24); 
      myText.setTextColor(Color.WHITE); 
      myText.setText("Booths"); 
      return myText; 
     } 
    }); 

    setSupportActionBar(toolbar); 
    android.support.v7.app.ActionBar mActionBar = getSupportActionBar(); 
    if (mActionBar != null) { 
     mActionBar.setDisplayHomeAsUpEnabled(true); 
     mActionBar.setElevation(4); 
    } 

ответ

4

лучший выбор, чтобы создать Toolbar и включают в себя макет в Toolbar, которая позволяет позиционирование:

<?xml version="1.0" encoding="utf-8?> 
<android.support.v7.widget.Toolbar 
    android:id="@+id/toolbar" 
    android:layout_width="fill_parent" 
    android:layout_height="?actionBarSize"> 
    <android.support.v7.widget.AppCompatTextView 
     android:text="My Title" 
     android:textSize="24sp" 
     android:textColor="#FFF" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center"/> 
</android.support.v7.widget.Toolbar> 

или в вашем конкретном использовании случае TextSwitcher

<?xml version="1.0" encoding="utf-8?> 
<android.support.v7.widget.Toolbar 
    android:id="@+id/toolbar" 
    android:layout_width="fill_parent" 
    android:layout_height="?actionBarSize"> 
     <TextSwitcher 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_gravity="center"> 
      <android.support.v7.widget.AppCompatTextView 
        android:text="My Title" 
        android:textSize="24sp" 
        android:textColor="#FFF" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"/> 
     </TextSwitcher> 
</android.support.v7.widget.Toolbar> 
0

Я предполагаю, что вы пытаетесь оживить название панели инструментов, так вот что я сделал, чтобы управлять этим:

-Первый вам нужен FrameLayout родителя для названия так, когда вы анимировать его вы не пересекаться с некоторыми иконками (в первую очередь значок ящика)

-Тогда приходит простой TextView, который является заголовком, просто используйте стиль ToolBarTitle, и вам больше не понадобится ничего.

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:app="http://schemas.android.com/apk/res-auto" 
android:id="@+id/toolbar" 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:layout_gravity="" 
android:background="?attr/colorPrimary" 
android:fitsSystemWindows="true" 
android:minHeight="?attr/actionBarSize" 
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" > 

<!-- This layout is used so the animation for the title view,does not overlap the drawer icon --> 

<FrameLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_gravity="" > 

    <TextView 
     android:id="@+id/toolbar_title" 
     style="@style/ToolbarTitle" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" /> 
</FrameLayout> 

При раздувать расположение панелей инструментов, убедитесь, что установлено оригинальное название панели инструментов в пустую строку, так это обыкновение пересекаться наш обычай

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    toolbar.setTitle(""); 

    toolbarTitle = (TextView) toolbar.findViewById(R.id.toolbar_title); 

Теперь вы можете легко анимировать название, как вы хотите, вот моя реализация, которая анимирует заголовок, скользящий слева и сдвигающийся влево, каждый раз, когда я меняю название.

/** 
* Changes the action bar title. 
*/ 
@Override 
public void setTitle(final CharSequence title) { 
    mTitle = title; 
    Animation makeOut = AnimationUtils.makeOutAnimation(
      MainMenuActivity.this, false); 
    makeOut.setAnimationListener(new AnimationListener() { 

     @Override 
     public void onAnimationEnd(Animation animation) { 
      toolbarTitle.setText(title); 
      toolbarTitle.startAnimation(AnimationUtils.makeInAnimation(
        MainMenuActivity.this, true)); 
     } 

     @Override 
     public void onAnimationRepeat(Animation animation) { 

     } 

     @Override 
     public void onAnimationStart(Animation animation) { 

     } 
    }); 
    toolbarTitle.startAnimation(makeOut); 

} 
Смежные вопросы