ActionBar导航(下拉列表)

阅读更多

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

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

	public ArrayAdapter getAdapter() {
		return adapter;
	}
}

 MyDropDownListenser.java——添加fragment。

public class MyDropDownListenser implements OnNavigationListener {
	private FragmentManager mFm;
	private ArrayList mFragmentsList;
	
	public MyDropDownListenser(FragmentManager fm,
			ArrayList 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导航(下拉列表)_第1张图片
 

Android2.3模拟器效果图

  • ActionBar导航(下拉列表)_第2张图片
  • 大小: 39.9 KB
  • 查看图片附件

你可能感兴趣的:(ActionBar,Spinner,Fragment)