2016-03-22 3 views
4

Здравствуйте, я создал макет вкладки в своей деятельности. Это главный .xml файл:Выровнять значки в макете вкладок влево

<?xml version="1.0" encoding="utf-8"?> 
<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="com.xxxxxx.eventmanager.EventDetailsActivity"> 

    <android.support.design.widget.AppBarLayout 
     android:layout_height="wrap_content" 
     android:layout_width="match_parent" 
     android:id="@+id/toolbarContainer" 
     android:theme="@style/AppTheme.AppBarOverlay"> 

     <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" 
      app:popupTheme="@style/AppTheme.PopupOverlay" /> 

    </android.support.design.widget.AppBarLayout> 

    <android.support.design.widget.TabLayout 
     android:id="@+id/tab_layout" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/toolbarContainer" 
     android:background="?attr/colorPrimary" 
     android:elevation="6dp" 
     android:minHeight="?attr/actionBarSize" 
     app:tabTextColor="@color/colorLight" 
     app:tabSelectedTextColor="@color/colorAccent" 
     android:textAlignment="" 
     android:theme="@style/AppTheme"/> 

    <android.support.v4.view.ViewPager 
     android:id="@+id/pager" 
     android:layout_width="match_parent" 
     android:layout_height="fill_parent" 
     android:layout_below="@id/tab_layout"/> 

</RelativeLayout> 

И это мой .java класс: Однако в настоящее время enter image description here

:

package com.xxxxxx.eventmanager; 

import android.graphics.drawable.Drawable; 
import android.support.design.widget.TabLayout; 
import android.support.v13.app.FragmentPagerAdapter; 
import android.support.v4.view.ViewPager; 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.Toolbar; 
import android.view.Menu; 
import android.view.MenuItem; 

import com.xxxxxx.eventmanager.adapters.EventPagerAdapter; 

public class EventDetailsActivity extends AppCompatActivity { 

    /** 
    * The {@link android.support.v4.view.PagerAdapter} that will provide 
    * fragments for each of the sections. We use a 
    * {@link FragmentPagerAdapter} derivative, which will keep every 
    * loaded fragment in memory. If this becomes too memory intensive, it 
    * may be best to switch to a 
    * {@link android.support.v13.app.FragmentStatePagerAdapter}. 
    * 
    * private SectionsPagerAdapter mSectionsPagerAdapter; 
    * 
    */ 

    private Toolbar toolbar; 

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

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

     TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout); 
     tabLayout.addTab(tabLayout.newTab().setText("Details").setIcon(R.mipmap.ic_details)); 
     tabLayout.addTab(tabLayout.newTab().setText("Sales").setIcon(R.mipmap.ic_sales)); 
     tabLayout.addTab(tabLayout.newTab().setText("Purchases").setIcon(R.mipmap.ic_purchase)); 
     tabLayout.setTabGravity(TabLayout.GRAVITY_FILL); 

     final ViewPager viewPager = (ViewPager) findViewById(R.id.pager); 
     final EventPagerAdapter adapter = new EventPagerAdapter 
       (getSupportFragmentManager(), tabLayout.getTabCount()); 
     viewPager.setAdapter(adapter); 
     viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); 
     tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { 
      @Override 
      public void onTabSelected(TabLayout.Tab tab) { 
       viewPager.setCurrentItem(tab.getPosition()); 
      } 

      @Override 
      public void onTabUnselected(TabLayout.Tab tab) { 

      } 

      @Override 
      public void onTabReselected(TabLayout.Tab tab) { 

      } 
     }); 

    } 


    @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_event_details, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

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

     return super.onOptionsItemSelected(item); 
    } 

} 

Теперь в настоящее время вкладка показывает, как это Я бы хотел, чтобы значки отображались в левой части текста, а не поверх текста.

ответ

0

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

TextView newTab = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null); 
newTab.setText("tab1"); //tab label txt 
newTab.setCompoundDrawablesWithIntrinsicBounds(your_drawable_icon_here, 0, 0, 0); 
tabLayout.getTabAt(tab_index_here_).setCustomView(newTab); 
0

Ответ дается @Tjerkw это нормально только, что это не цикл через вкладку всего. Я предполагаю, что правильное решение должно быть это

for (int i = 0; i < tabLayout.getTabCount(); i++) { 
    yourlinearlayout = (LinearLayout) LayoutInflater.from(getContext()).inflate(R.layout.title_text, null); 
    tab_text = (TextView) yourlinearlayout.findViewById(R.id.tabContent); 
      tab_text.setText(" " + tab_titles[i]); 
    tab_text.setCompoundDrawablesWithIntrinsicBounds(tabicons[i], 0, 0, 0); 
     tabLayout.getTabAt(i).setCustomView(tab_text);} 

и .xml раскладки ресурса, представляющий R.layout.title_text будет

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:gravity="center"> 
<TextView 
    android:id="@+id/tabContent" 
    android:layout_width="wrap_content" 
    android:layout_height="match_parent" 
    android:textAlignment="center" 
    android:textColor="@android:color/white" 
    android:gravity="center"/> 

наконец, tabicons[i] и закладка tab_titles[i] просто строковые массивы, содержащие их соответствующего содержимое. Я знаю этот вопрос старый, но я недавно столкнулся с этим, и я уверен, что кому-то еще может понадобиться это

0

TabLayout также поддерживает пользовательские представления вместо TabView.

1.Create макет элемент вкладки .The Основная идея заключается в том, мы должны использовать указать идентификатор для ImageView @android: ID/значок и TextView @android: ид/text1

R.layout.custom_tab_item

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="?attr/actionBarSize" 
    android:orientation="horizontal"> 

    <ImageView 
     android:id="@android:id/icon" 
     android:layout_width="32dp" 
     android:layout_height="32dp" 
     android:padding="4dp" 
     android:layout_gravity="center_vertical"/> 

    <TextView 
     android:id="@android:id/text1" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:textSize="@dimen/large_text" 
     android:padding="4dp" 
     android:layout_gravity="center_vertical" 
     android:gravity="center_vertical"/> 

</LinearLayout> 

2. И XML файл TabLayout

<android.support.design.widget.TabLayout 
     xmlns:app="http://schemas.android.com/apk/res-auto" 
     android:id="@+id/tab_layout" 
     android:layout_width="match_parent" 
     android:layout_height="?attr/actionBarSize" 
     android:background="?attr/colorPrimary" 
     app:tabMaxWidth="0dp" 
     app:tabGravity="fill" 
     app:tabMode="fixed" 
     android:theme="@style/vocabularyTheme.ActionBar" /> 

3. Создание tabLayout с помощью пользовательских представлений и удалить нижнюю границу, которая была создана по умолчанию 8dp

mTabLayout = (TabLayout) findViewById(R.id.tab_layout);  
mTabLayout.addTab(createTab(text1,icon1)); 
mTabLayout.addTab(createTab(text2,icon2)); 

private TabLayout.Tab createTab(String text, Drawable icon){ 
    TabLayout.Tab tab = mTabLayout.newTab().setText(text).setIcon(icon).setCustomView(R.layout.custom_tab_item); 

    // remove imageView bottom margin 
    if (tab.getCustomView() != null){ 
     ImageView imageView = (ImageView) tab.getCustomView().findViewById(android.R.id.icon); 
     ViewGroup.MarginLayoutParams lp = ((ViewGroup.MarginLayoutParams) imageView.getLayoutParams()); 
     lp.bottomMargin = 0; 
     imageView.requestLayout(); 
    } 

    return tab; 
} 

Ожидаемый результат.

Align Icons in Tab Layout To The Left

0

Вы должны ввести ActionMenuView внутри Toolbar.

От Google Official docs«ActionMenuView является презентацией серии опций меню как View. Он предоставляет несколько топ вариантов уровня как кнопки действий, а проливать остальные параметры более в виде пунктов в меню переполнения. Это позволяет приложениям представить пакеты действий, связанных с конкретным или повторяющимся контентом ».

Например,

<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/tToolbar" 
    android:layout_height="?attr/actionBarSize" 
    android:layout_width="match_parent" 
    android:background="?attr/colorPrimary" 
    android:gravity="center_vertical|start" 
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" 
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"> 

    <android.support.v7.widget.ActionMenuView 
     android:id="@+id/amvMenu" 
     android:layout_width="match_parent" 
     android:layout_height="?attr/actionBarSize"/> 
</android.support.v7.widget.Toolbar> 

И на вашей деятельности,

Toolbar t = (Toolbar) findViewById(R.id.tToolbar); 
    amvMenu = (ActionMenuView) t.findViewById(R.id.amvMenu); 
    amvMenu.setOnMenuItemClickListener(new ActionMenuView.OnMenuItemClickListener() { 
     @Override 
     public boolean onMenuItemClick(MenuItem menuItem) { 
     return onOptionsItemSelected(menuItem); 
     } 
    }); 
Смежные вопросы