2015-01-28 4 views
1

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

Допустим, я хочу этот результат точно

enter image description here

Но закладка оригинал выглядит

enter image description here

Есть ли способ создать собственную компоновку вкладок?

+0

«Есть ли способ, чтобы создать мой собственный макет вкладки? " => Конечно. Теперь попробуйте, и вернитесь с вопросом программирования, а не с запросом на кодирование. – 2Dee

ответ

1

Часы this video из команды Android Dev показывает, как использовать Sliding Tabs

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

Создать файл называется SmartFragmentStatePagerAdapter.java и введите этот код:

package com.package.name; 

import android.support.v4.app.Fragment; 
import android.support.v4.app.FragmentManager; 
import android.support.v4.app.FragmentStatePagerAdapter; 
import android.util.SparseArray; 
import android.view.ViewGroup; 

/* 
Extension of FragmentStatePagerAdapter which intelligently caches 
all active fragments and manages the fragment lifecycles. 
Usage involves extending from SmartFragmentStatePagerAdapter as you would any other PagerAdapter. 
*/ 
public abstract class SmartFragmentStatePagerAdapter extends FragmentStatePagerAdapter { 
    // Sparse array to keep track of registered fragments in memory 
    private SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>(); 

public SmartFragmentStatePagerAdapter(FragmentManager fragmentManager) { 
    super(fragmentManager); 
} 

// Register the fragment when the item is instantiated 
@Override 
public Object instantiateItem(ViewGroup container, int position) { 
    Fragment fragment = (Fragment) super.instantiateItem(container, position); 
    registeredFragments.put(position, fragment); 
    return fragment; 
} 

// Unregister when the item is inactive 
@Override 
public void destroyItem(ViewGroup container, int position, Object object) { 
    registeredFragments.remove(position); 
    super.destroyItem(container, position, object); 
} 

// Returns the fragment for the position (if instantiated) 
public Fragment getRegisteredFragment(int position) { 
    return registeredFragments.get(position); 
} 
} 

В классе PageAdapter это сделать:

public class PageAdapter extends SmartFragmentStatePagerAdapter { 

    final String TAG = "PageAdapter"; 

    ArrayList<Fragment> cards = new ArrayList<Fragment>(); 

    private final String[] TITLES = { getResources().getString(R.string.home) , getResources().getString(R.string.second_home) , getResources().getString(R.string.third_home) , getResources().getString(R.string.fourth_home) }; 

    FragmentManager fm = null; 

    public PageAdapter(FragmentManager fm) { 
     super(fm); 
     this.fm = fm;  
     Log.d(TAG, "Tiles are being created"); 
    } 

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

    @Override 
    public CharSequence getPageTitle(int position){ 
     return TITLES[position];   
    } 

    @Override 
    public Fragment getItem(int position) { 
     Fragment card = CardFragment.newInstance(position); 
     Log.d(TAG, "getItem has been called"); 
     cards.add(card); 
     return card; 
    } 
    } 

Мои CardFragment.class:

package com.package.name; 

import java.util.List; 

import android.content.Context; 
import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.support.v4.app.FragmentManager; 
import android.util.Log; 
import android.util.TypedValue; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.FrameLayout; 
import android.widget.FrameLayout.LayoutParams; 

public class CardFragment extends Fragment{ 

final String TAG = "CardFragment"; 

ViewGroup cards = null; 
FrameLayout fl = null; 

static Context context; 

static FragmentManager fragmentManager = null; 

private static final String ARG_POSITION = "position"; 

private int position; 

public static CardFragment newInstance(int position) { 
    CardFragment f = new CardFragment(); 
    Bundle b = new Bundle(); 
    b.putInt(ARG_POSITION, position); 
    f.setArguments(b); 
    return f; 
} 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    fragmentManager = this.getFragmentManager(); 
    position = getArguments().getInt(ARG_POSITION); 
} 


@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    cards = container; 
    View v = null; 
    if(fragmentManager == null){ 
     fragmentManager = this.getFragmentManager(); 
    } 

    switch (position){ 
     case 0: 
      v = inflater.inflate(R.layout.tab_home,null); 
      Log.d(TAG, "Layout for position " + position + " inflated"); 
      break; 
     case 1: 
      v = inflater.inflate(R.layout.tab_second_home,null); 
      Log.d(TAG, "Layout for position " + position + " inflated"); 
      break; 
     case 2: 
      v = inflater.inflate(R.layout.tab_third_home,null); 
      Log.d(TAG, "Layout for position " + position + " inflated"); 
      break; 
     case 3: 
      v = inflater.inflate(R.layout.tab_fourth_home,null); 
      Log.d(TAG, "Layout for position " + position + " inflated"); 
      break; 
    } 



    LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); 

    fl = new FrameLayout(getActivity()); 
    fl.setLayoutParams(params); 

    final int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources() 
      .getDisplayMetrics()); 


    params.setMargins(margin, margin, margin, margin); 


    fl.addView(v); 
    return fl; 
} 

}

И, наконец, сделать это в OnCreate():

tabs = (HorizontalScrollView)v.findViewById(R.id.tabs); 
     pager = (ViewPager)v.findViewById(R.id.pager); 
     adapter = new PageAdapter(getSupportFragmentManager()); 
     // Initialize the ViewPager and set an adapter 

     pager.setAdapter(adapter); 

     final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources() 
       .getDisplayMetrics()); // The space between pages. 

     pager.setPageMargin(pageMargin); 

     // Bind the tabs to the ViewPager 
     tabs.setViewPager(pager); 

В общей сложности будет 4 страницы, созданные из-за ваших НАЗВАНИЙ содержит 4 строки. Редактировать класс CardFragment использовать различные схемы, для удобства я назвал их tab_home, tab_second_home, tab_third_home и tab_fourth_home Если вы хотите корневой макет использования карты это:

Fragment card = adapter.getRegisteredFragment(pager.getCurrentItem()); 

if(card != null){ 
        textView = (TextView)card.getView().findViewById(R.id.textView); // This will use the textView you are seeing on the screen of the selected page right now. Change this to any view you would like to edit 

        }else{ 
         System.out.println("card is null nothing has been added to the layout!"); 
        } 
-1

Чтобы настроить ActionBar с помощью пользовательского макета в Android

создать файл XML пользовательский макет для ActionBar (в соответствии с вашими потребностями)

custom_actionbar.xml

<TextView 
    android:id="@+id/title_text" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_centerInParent="true" 
    android:textAllCaps="true" 
    android:textAppearance="?android:attr/textAppearanceLarge" 
    android:textColor="#fff" 
    android:textStyle="bold" /> 

<ImageView 
    android:id="@+id/imageView1" 
    android:layout_width="35dp" 
    android:layout_height="35dp" 
    android:layout_alignParentLeft="true" 
    android:layout_centerVertical="true" 
    android:layout_marginLeft="8dp" 
    android:src="@drawable/ic_launcher" /> 

<ImageButton 
    android:id="@+id/imageButton" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentRight="true" 
    android:layout_centerVertical="true" 
    android:layout_marginRight="8dp" 
    android:background="@null" 
    android:src="@android:drawable/ic_menu_rotate" /> 

Вы можете надуть этот обычай вид ActionBar с помощью метода setCustomView(). Давайте посмотрим на фрагменте кода ниже

ActionBar mActionBar = getActionBar(); 
    mActionBar.setDisplayShowHomeEnabled(false); 
    mActionBar.setDisplayShowTitleEnabled(false); 
    LayoutInflater mInflater = LayoutInflater.from(this); 

    View mCustomView = mInflater.inflate(R.layout.custom_actionbar, null); 
    TextView mTitleTextView = (TextView) mCustomView.findViewById(R.id.title_text); 
    mTitleTextView.setText("My Own Title"); 

    ImageButton imageButton = (ImageButton) mCustomView 
      .findViewById(R.id.imageButton); 
    imageButton.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View view) { 
      Toast.makeText(getApplicationContext(), "Refresh Clicked!", 
        Toast.LENGTH_LONG).show(); 
     } 
    }); 

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

Выход

enter image description here

вы можете определить любой макет в вашем XML custom_actionbar.xml. его просто пример

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