2016-03-10 5 views
2

У меня проблема с отображением пробела в верхней части фрагмента, когда я делаю actionBar.hide() (Кстати, я не вижу этого пробела на симуляторе, только на реальном устройстве). Я пробовал this answer и that one, но ничего не работает. Этот фрагмент находится внутри MainActivity, который загружает разные фрагменты, когда я нажимаю на меню. Это единственный фрагмент, в котором actionBar (который является обычным) должен быть скрытым, поэтому я не могу установить флаг полноэкранного режима в методе MainActivity onCreate(). Как я могу перерисовать представление, чтобы исчезло пустое поле actionBar?Снять зазор в верхней части фрагмента, когда actionBar скрыт

Вот как это выглядит сейчас:

enter image description here

Это mainActivty где я загружаю фрагмент:

public void onCreate(Bundle savedInstanceState) { 

     getWindow().requestFeature(Window.FEATURE_ACTION_BAR); 
     getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY); 
     super.onCreate(savedInstanceState); 

     showActionBar(); 

     if(Build.VERSION.SDK_INT >= 21){ 
      getWindow().getDecorView().setSystemUiVisibility(
        View.SYSTEM_UI_FLAG_LAYOUT_STABLE 
          | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); 
     } 
     setContentView(R.layout.activity_main); 
     setUpMenu(); 
} 

При клике на меню, я изменить фрагмент соответственно:

@Override 
    public void onClick(View view) { 
     if (view == itemProfile){ 
      mActionBar.hide(); 
      ProfileFragment profile = new ProfileFragment(); 
      profile.setUser(AppController.getInstance().getLoggedInUser()); 
      changeFragment(profile); 
     } 
} 

И пользовательское действиеBar

private void showActionBar() { 
     mActionBar = getSupportActionBar(); 
     mActionBar.setDisplayShowHomeEnabled(false); 
     mActionBar.setDisplayShowTitleEnabled(false); 
     ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#ffffff")); 
     mActionBar.setBackgroundDrawable(colorDrawable); 
     LayoutInflater mInflater = LayoutInflater.from(this); 

     View mCustomView = mInflater.inflate(R.layout.custom_actionbar, null); 
     mTitleTextView = (TextView) mCustomView.findViewById(R.id.title_text); 
     mLogo = (ImageView) mCustomView.findViewById(R.id.logo); 

     ImageButton menuButton = (ImageButton) mCustomView 
       .findViewById(R.id.menu); 
     menuButton.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View view) { 
       if (resideMenu.isOpened()) { 
        resideMenu.closeMenu(); 
       } else { 
        resideMenu.openMenu(); 
       } 
      } 
     }); 

     ImageButton mapButton = (ImageButton) mCustomView 
       .findViewById(R.id.map); 
     mapButton.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View view) { 
       Intent i = new Intent(getApplicationContext(), MapsActivity.class); 
       startActivity(i); 
      } 
     }); 

     mActionBar.setCustomView(mCustomView); 
     mActionBar.setDisplayShowCustomEnabled(true); 

    } 

Моя тема:

<style name="AppTheme" parent="Theme.AppCompat.Light"> 
    <item name="android:colorPrimaryDark">@android:color/black</item> 
    <item name="android:windowActionBarOverlay">true</item> 
</style> 

Мой mainActivity расположение:

<?xml version="1.0" encoding="utf-8"?> 
<FrameLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:fitsSystemWindows="true" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 

    <FrameLayout 
     android:id="@+id/main" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent"> 

     <LinearLayout 
      android:orientation="vertical" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent"> 

      <FrameLayout 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:orientation="vertical" 
       android:id="@+id/main_fragment"> 
      </FrameLayout> 

     </LinearLayout> 
    </FrameLayout> 
</FrameLayout> 

Мой заказ ActionBar

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

    <FrameLayout 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:background="@color/transparent"> 

     <TextView 
     android:id="@+id/title_text" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:padding="7dp" 
     android:fontFamily="sans-serif-light" 
     android:text="@string/app_title" 
     android:textSize="@dimen/textsize_large" 
     android:textColor="@android:color/black" 
     android:layout_gravity="center" 
     android:visibility="gone"/> 

     <ImageView 
      android:id="@+id/logo" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:padding="7dp" 
      android:layout_gravity="center" 
      android:src="@drawable/logo" 
      android:background="@color/transparent" /> 

     <ImageButton android:src="@drawable/earth" 
      android:background="?attr/actionBarItemBackground" 
      android:layout_width="?attr/actionBarSize" 
      android:layout_height="20dp" 
      android:scaleType="centerInside" 
      android:id="@+id/map" 
      android:layout_alignParentRight="true" 
      android:layout_alignParentTop="true" 
      android:layout_gravity="right|center_vertical" 
      android:layout_marginRight="-15dp" 
      android:tint="@color/black"/> 

     <ImageButton android:src="@drawable/titlebar_menu_selector" 
      android:background="?attr/actionBarItemBackground" 
      android:layout_width="?attr/actionBarSize" 
      android:layout_height="match_parent" 
      android:scaleType="centerInside" 
      android:id="@+id/menu" 
      android:layout_alignParentLeft="true" 
      android:layout_alignParentTop="true" 
      android:layout_marginLeft="-15dp" 
      android:layout_gravity="left|center_vertical" 
      android:tint="@color/black"/> 

    </FrameLayout> 

</RelativeLayout> 

Любая помощь будет большим, я воюю с это уже несколько дней, и я действительно не знаю, что т делать ...

ответ

1

заменить

mActionBar.hide(); 

с

mActionBar.setVisibility(View.GONE); 

Вам нужно добавить панель инструментов в макете активность. Найдите нижеприведенный фрагмент кода для простой компоновки панели инструментов.

<android.support.v7.widget.Toolbar 
    android:id="@+id/toolbar" 
    android:minHeight="?attr/actionBarSize" 
    android:background="#2196F3" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"> 
</android.support.v7.widget.Toolbar> 

Применить тему к деятельности. Здесь на этом шаге вам нужно применить тему, которую мы создали на шаге 1 к вашей деятельности. Это можно сделать, используя атрибут android: theme в вашем приложении AndroidManifest.xml.

<activity 
     android:name="com.javatechig.sample.MyActivity" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme" > 
</activity> 

Теперь вы почти готовы. Вам просто нужно создать экземпляр панели инструментов и добавить ее в свою деятельность с помощью метода setSupportActionBar (Toolbar).

import android.support.v7.app.ActionBarActivity; 
import android.support.v7.widget.Toolbar; 

public class MyActivity extends ActionBarActivity{ 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_my); 

    // Set a toolbar to replace the action bar. 
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 
} 
} 

Посетите ниже ссылку, чтобы узнать больше ..

Using Toolbar as ActionBar

+0

Он не работает, к сожалению, теперь она показывает пустое пространство вместо черной. –

+0

u ahve использовать панель инструментов вместо панели действий ... затем попытаться применить вышеуказанный код к панели инструментов ... –

+0

Как я могу использовать панель инструментов вместо панели действий? –

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