下面通过适配器添加下拉列表在ActionBar上面:
package com.example.androidnavigationmode; import android.annotation.SuppressLint; import android.app.ActionBar; import android.app.ActionBar.OnNavigationListener; import android.app.Activity; import android.app.Fragment; import android.app.FragmentTransaction; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.SpinnerAdapter; import android.widget.TextView; @SuppressLint("ValidFragment") public class HelloActionBarActivity extends Activity{ private static final String TAG = "HelloActionBarActivity"; public final static int TAB_INDEX_1 = 0; public final static int TAB_INDEX_2 = 1; public final static int TAB_INDEX_3 = 2; public final static int TAB_COUNT = 3; private ActionBar actionBar; private OnNavigationListener mOnNavigationListener; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.v(TAG, "onCreate"); setContentView(R.layout.main); actionBar = getActionBar(); //设置AcitonBar的操作模型 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.action_list, android.R.layout.simple_spinner_dropdown_item); mOnNavigationListener = new OnNavigationListener() { // Get the same strings provided for the drop-down's ArrayAdapter String[] strings = getResources().getStringArray(R.array.action_list); @Override public boolean onNavigationItemSelected(int position, long itemId) { // Create new fragment from our own Fragment class ListContentFragment newFragment = new ListContentFragment(); /*FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.context, newFragment, strings[position]); ft.commit();*/ return true; } }; actionBar.setListNavigationCallbacks(mSpinnerAdapter, mOnNavigationListener); } public class ListContentFragment extends Fragment{ private String mText; @Override public void onAttach(Activity activity) { // This is the first callback received; here we can set the text for // the fragment as defined by the tag specified during the fragment transaction super.onAttach(activity); mText = getTag(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // This is called to define the layout for the fragment; // we just create a TextView and set its text to be the fragment tag TextView text = new TextView(getActivity()); text.setText(mText); return text; } } }
其中一个列表名称列表:
<?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="action_list"> <item >item_list1</item> <item >item_list2</item> <item >item_list3</item> </string-array> </resources>