创建自定义android选项卡

时间:2015-01-28 16:52:53

标签: android android-layout android-tabhost android-tabs

我想创建自己的标签,我想拥有自己的布局

假设我想要这个结果

enter image description here

但原始标签看起来像

enter image description here

有没有办法创建自己的标签布局?

3 个答案:

答案 0 :(得分:1)

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

并根据需要进行修改

答案 1 :(得分:1)

观看Android Dev团队的this video,了解如何使用滑动标签

如果你想动态编辑页面的布局,我得到了一个方便的课程:

创建名为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个页面,因为您的TITLES包含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!");
                   }

答案 2 :(得分:-1)

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

<强>输出

enter image description here

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