ActionBarSherlock的NAVIGATION_MODE_LIST模式

与ActionBar一样ActionBarSherlock也提供了NAVIGATION_MODE_LIST模式,即在操作栏上实现下拉的形式,方便用户进行选择,关键步骤是要实现一个OnNavigationListener接口,以便选择下拉选项时切换不同的视图。

MainActivity.java代码:

public class MainActivity extends SherlockFragmentActivity {

	/*定义一个ActionBar*/
	private ActionBar actionBar;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		/*设置一个adapter*/
		SpinnerAdapter adapter = ArrayAdapter.createFromResource(this, R.array.student, android.R.layout.simple_list_item_1);
		
		/*得到ActionBar*/
		actionBar = this.getSupportActionBar();
		/*将actionBar的操作模型设置为NAVIGATION_MODE_LIST*/
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
		
		/*设置下拉的回调事件*/
		actionBar.setListNavigationCallbacks(adapter, new MyNavigationListener());
		
	}

	/**
	 * 创建onNavigationListener内部监听器,以实现选择下拉列表中选项切换视图的效果
	 */
	class MyNavigationListener implements OnNavigationListener{

		/*从arrays.xml文件中获取字符数组*/
		String[] listNames = getResources().getStringArray(R.array.student);
		
		/*选择下拉菜单项的时候,将Activity的内容置换为对应的Fragment*/
		public boolean onNavigationItemSelected(int itemPosition, long itemId) {
			
			/*生成自定Fragment*/
			StudentInfo student = new StudentInfo();
			FragmentManager manager = getSupportFragmentManager();
			
			FragmentTransaction transaction = manager.beginTransaction();
			
			/*将Activity中的内容替换成为对应的Fragment*/
			transaction.replace(android.R.id.content, student, listNames[itemPosition]);
			
			transaction.commit();
			
			return true;
		}
		
	}
	
	public boolean onCreateOptionsMenu(Menu menu) {

		getSupportMenuInflater().inflate(R.menu.main, menu);
		
		return true;
	}

}

StudentInfo.java代码:

public class StudentInfo extends Fragment {

	/* Fragment对应的标签,当Fragment依附于Activity时得到 */
	private String tag;

	@Override
	public void onAttach(Activity activity) {

		super.onAttach(activity);

		tag = this.getTag();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		TextView textView = new TextView(getActivity());

		textView.setText(tag);

		return textView;
	}
	
	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}
}

activity_main.xml:



    



values/arrays.xml代码:



    
    
        廖*民
        刘*星
        钟*建
        罗*明
    



demo效果展示:

ActionBarSherlock的NAVIGATION_MODE_LIST模式_第1张图片


下载demo:http://download.csdn.net/detail/lzm1340458776/7320729

你可能感兴趣的:(Android学习)