欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ActionBar导航(下拉列表)

程序员文章站 2022-06-03 13:00:14
...

ActionBar导航(下拉列表)

在Activity中添加Adapter适配器,实现OnNavigationListener接口。将fragment添加到MyDropDownListenser中,并把下拉列表标题添加到MySpinnerAdapter里。

设置setNavigationMode为NAVIGATION_MODE_LIST,向setListNavigationCallbacks中添加适配器和接口。

下拉列表有两种样式:simple_spinner_dropdown_item(带圆圈)和simple_spinner_item(不带圆圈)。为兼容Android2.x请使用support_simple_spinner_dropdown_item(不带圆圈)。

import android.support.v7.app.ActionBarActivity;
private ActionBar actionBar;
private FragmentManager fm;
private ArrayList<Fragment> mFragmentsList;
private String[] dataTag;
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
	actionBar = getSupportActionBar();
	fm = getSupportFragmentManager();
	//向ArrayList中添加fragment
	mFragmentsList = new ArrayList<Fragment>();
	mFragmentsList.add(new MyFragmentA());
	mFragmentsList.add(new MyFragmentB());
	//向dataTag添加标签
	dataTag =new String[]{"页 面 一","页 面 二"};
	//设置SpinnerAdapter
	MySpinnerAdapter Adapter = new MySpinnerAdapter(this,
			support_simple_spinner_dropdown_item, dataTag);
	//NavigationSpinner配置
	actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
	actionBar.setListNavigationCallbacks(Adapter.getAdapter(),
	//设置DropDownListenser
			new MyDropDownListenser(fm, mFragmentsList));
}

 MySpinnerAdapter.java——设置下拉列表。

public class MySpinnerAdapter {
	private ArrayAdapter<String> adapter;

	public MySpinnerAdapter(Context context, int textArrayResId, String[] mItems) {
		// TODO Auto-generated constructor stub
		this.adapter = new ArrayAdapter<String>(context,
				support_simple_spinner_dropdown_item, mItems);
		this.adapter.setDropDownViewResource(textArrayResId);
	}

	public ArrayAdapter<String> getAdapter() {
		return adapter;
	}
}

 MyDropDownListenser.java——添加fragment。

public class MyDropDownListenser implements OnNavigationListener {
	private FragmentManager mFm;
	private ArrayList<Fragment> mFragmentsList;
	
	public MyDropDownListenser(FragmentManager fm,
			ArrayList<Fragment> fragmentsList) {
		// TODO Auto-generated constructor stub
		this.mFm = fm;
		this.mFragmentsList = fragmentsList;
	}

	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		// TODO Auto-generated method stub
		FragmentTransaction transaction = mFm.beginTransaction();
		// 将Activity中的内容替换成对应选择的Fragment
		transaction.replace(android.R.id.content,
				mFragmentsList.get(itemPosition));
		transaction.commit();
		return true;
	}

}


ActionBar导航(下拉列表)
            
    
    博客分类: Android 笔记 ActionBarSpinnerFragmentNAVIGATION_MODE_LIST 
 

Android2.3模拟器效果图

  • ActionBar导航(下拉列表)
            
    
    博客分类: Android 笔记 ActionBarSpinnerFragmentNAVIGATION_MODE_LIST 
  • 大小: 39.9 KB