创建自定义 android 标签

create custom android tabs

我想创建自己的选项卡,我想拥有自己的布局

假设我想要这个结果

但原来的标签看起来像

有没有办法创建我自己的选项卡布局?

查看滑动标签示例代码:https://developer.android.com/samples/SlidingTabsBasic/index.html

随意修改

在 Android

中使用自定义布局自定义 ActionBar

为您的 ActionBar 创建自定义布局 xml 文件(根据您的需要)

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" />

您可以通过 setCustomView() 方法将此自定义视图扩展到 ActionBar。让我们看看下面的代码片段

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);

输出

您可以在 xml custom_actionbar.xml 中定义任何布局。这只是一个例子

观看 Android 开发团队的 this video 演示如何使用滑动标签

如果你想动态编辑页面的布局,我有一个方便的class:

创建一个名为 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 class 中执行此操作:

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 个页面,因为您的 TITLES 包含 4 个字符串。 编辑 CardFragment class 以使用不同的布局,为方便起见,我将它们称为 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!");
                   }