2015-10-07 2 views
3

В моем приложении я использую вкладки панели действий внизу. Я искал много учебников, но я не понимаю решения. Большинство ответов сказали, что они используют TabActivity, но это устарело. Так может ли кто-нибудь сказать мне, как можно подойти к этому?Как установить вкладки внизу, а также скрыть верхнюю панель действий?

ответ

0

Шаг 1 - Создайте пользовательский макет для вашей панели инструментов.

<?xml version="1.0" encoding="utf-8"?> 
    <android.support.v7.widget.Toolbar 
     xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:app="http://schemas.android.com/apk/res-auto" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" 
     app:popupTheme="@style/ThemeOverlay.AppCompat.Light"> 

    </android.support.v7.widget.Toolbar> 

Шаг 2 - Включите этот макет в свой макет деятельности. Дайте ему нижнюю позицию.

<include 
    android:id="@+id/toolbar_main" 
    layout="@layout/main_toolbar" /> 

Шаг 3 - Вызовите панель инструментов в свою деятельность и выполните. Он будет вести себя как любая панель инструментов, но расположенная внизу.

3

Это пример

Toolbar toolbarBottom = (Toolbar) findViewById(R.id.toolbar_bottom); 
    toolbarBottom.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { 
     @Override 
     public boolean onMenuItemClick(MenuItem item) { 
      switch(item.getItemId()){ 
       case R.id.action_settings: 
        // TODO 
        break; 
       // TODO: Other cases 
      } 
      return true; 
     } 
    }); 
    // Inflate a menu to be displayed in the toolbar 
    toolbarBottom.inflateMenu(R.menu.menu_main); 

и это XML

<android.support.v7.widget.Toolbar 
    android:id="@+id/toolbar_bottom" 
    android:layout_height="wrap_content" 
    android:layout_width="match_parent" 
    android:background="?attr/colorPrimary" 
    android:layout_alignParentBottom="true" 
    android:minHeight="?attr/actionBarSize" /> 
14

Лучший способ реализации вкладок в настоящее время является использование TabLayout из библиотеки дизайна.

Вот пример TabLayout, выровненный в нижней части экрана.

Сначала установить зависимости в файле build.gradle:

dependencies { 
    compile fileTree(dir: 'libs', include: ['*.jar']) 
    compile 'com.android.support:appcompat-v7:23.0.1' 
    compile 'com.android.support:design:23.0.1' 
} 

Вот макет XML для основного вида деятельности:

<RelativeLayout 
    android:id="@+id/main_layout" 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context=".MainActivity"> 

    <android.support.v7.widget.Toolbar 
     android:id="@+id/toolbar" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_alignParentTop="true" 
     android:background="?attr/colorPrimary" 
     android:elevation="6dp" 
     android:minHeight="?attr/actionBarSize" 
     android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" 
     app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/> 

    <android.support.v4.view.ViewPager 
     android:id="@+id/viewpager" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_below="@id/toolbar"/> 

    <android.support.design.widget.TabLayout 
     android:id="@+id/tab_layout" 
     app:tabMode="fixed" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:background="?attr/colorPrimary" 
     android:elevation="6dp" 
     app:tabTextColor="#d3d3d3" 
     app:tabSelectedTextColor="#ffffff" 
     app:tabIndicatorColor="#ff00ff" 
     android:minHeight="?attr/actionBarSize" 
     android:layout_alignParentBottom="true" 
     /> 

</RelativeLayout> 

Вот код активность:

public class MainActivity extends AppCompatActivity { 

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

     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 

     // Get the ViewPager and set it's PagerAdapter so that it can display items 
     ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager); 
     PagerAdapter pagerAdapter = 
       new PagerAdapter(getSupportFragmentManager(), MainActivity.this); 
     viewPager.setAdapter(pagerAdapter); 

     // Give the TabLayout the ViewPager 
     TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout); 
     tabLayout.setupWithViewPager(viewPager); 

     // Iterate over all tabs and set the custom view 
     for (int i = 0; i < tabLayout.getTabCount(); i++) { 
      TabLayout.Tab tab = tabLayout.getTabAt(i); 
      tab.setCustomView(pagerAdapter.getTabView(i)); 
     } 
    } 


    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.menu_main, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     int id = item.getItemId(); 

     if (id == R.id.action_settings) { 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 

    class PagerAdapter extends FragmentPagerAdapter { 

     String tabTitles[] = new String[] { "Tab One", "Tab Two", "Tab Three", }; 
     Context context; 

     public PagerAdapter(FragmentManager fm, Context context) { 
      super(fm); 
      this.context = context; 
     } 

     @Override 
     public int getCount() { 
      return tabTitles.length; 
     } 

     @Override 
     public Fragment getItem(int position) { 

      switch (position) { 
       case 0: 
        return new BlankFragment(); 
       case 1: 
        return new BlankFragment(); 
       case 2: 
        return new MapFragment(); 
      } 

      return null; 
     } 

     @Override 
     public CharSequence getPageTitle(int position) { 
      // Generate title based on item position 
      return tabTitles[position]; 
     } 

     public View getTabView(int position) { 
      View tab = LayoutInflater.from(MainActivity.this).inflate(R.layout.custom_tab, null); 
      TextView tv = (TextView) tab.findViewById(R.id.custom_text); 
      tv.setText(tabTitles[position]); 
      return tab; 
     } 

    } 
} 

custom_tab.xml:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="match_parent" 
    android:layout_height="match_parent"> 
    <TextView 
     android:id="@+id/custom_text" 
     android:layout_width="wrap_content" 
     android:layout_height="match_parent" 
     android:background="?attr/selectableItemBackground" 
     android:gravity="center" 
     android:textSize="16dip" 
     android:textColor="#ffffff" 
     android:singleLine="true" 
     /> 
</LinearLayout> 

App тема в styles.xml:

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> 
    <!-- your app branding color for the app bar --> 
    <item name="colorPrimary">#3F51B5</item> 
    <!-- darker variant for the status bar and contextual app bars --> 
    <item name="colorPrimaryDark">#303F9F</item> 
    <!-- theme UI controls like checkboxes and text fields --> 
    <item name="colorAccent">#FF4081</item> 
</style> 

Результат:

enter image description here

enter image description here

Если вы хотите, чтобы скрыть ActionBar, просто удалите панель из макета XML , и удалите код панели инструментов из Activity, и обязательно используйте Theme.AppCompat.Light.NoActionBar в AppTheme. В результате этих изменений будет сделать его выглядеть следующим образом:

enter image description here

+0

Спасибо .. это работа для меня ... спасибо verymuch –

+0

Хорошей работы @Daniel – saintjab

+0

@ DANIEL-Nugent Как я могу установить розовый индикатор сверху вкладки? поскольку tablayout находится внизу, розовый индикатор имеет больше смысла, когда он находится наверху. – Felix

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