本文主要是介绍督促学习——ViewPager实现滑动的Preference页面且带ActionBar,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
直接上代码有时间具体分析:
1、MainActivity.java
public class MainActivity extends FragmentActivity implementsOnPageChangeListener {private int mActionBarOptions;private ViewPager mViewPager;private View mCustomView;private ImageView mScroll1;private ImageView mScroll2;private ImageView mScroll3;private ImageView mScroll4;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.custom_tab_on_top_content);mViewPager = (ViewPager) findViewById(R.id.pager);// mViewPager// .setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));mViewPager.setAdapter(new PagerAdapter(getSupportFragmentManager(),this));mViewPager.setOnPageChangeListener(this);// 设置页面分隔线mViewPager.setPageMargin(6);mViewPager.setPageMarginDrawable(android.R.drawable.divider_horizontal_bright);// 自定义 Tab View,并添加到ActionBar上(未设置DisplayOptions,不会显示)mCustomView = LayoutInflater.from(this).inflate(R.layout.custom_tab_view, null);// getParent().getActionBar().setCustomView(mCustomView);getActionBar().setCustomView(mCustomView);mScroll1 = (ImageView) mCustomView.findViewById(R.id.scroll_1);mScroll2 = (ImageView) mCustomView.findViewById(R.id.scroll_2);mScroll3 = (ImageView) mCustomView.findViewById(R.id.scroll_3);mScroll4 = (ImageView) mCustomView.findViewById(R.id.scroll_4);}@Overrideprotected void onResume() {super.onResume();ActionBar actionBar = getActionBar();mActionBarOptions = actionBar.getDisplayOptions();// 设置DisplayOptions,显示ActionBar自定义的ViewactionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM,ActionBar.DISPLAY_SHOW_CUSTOM | mActionBarOptions);setCurrentScroll(mViewPager.getCurrentItem());}@Overrideprotected void onPause() {super.onPause();getActionBar().setDisplayOptions(mActionBarOptions,ActionBar.DISPLAY_SHOW_CUSTOM | mActionBarOptions);}public void onTabClick(View view) {Log.d("TAG", "onTabClick" + view.getId());switch (view.getId()) {case R.id.tab_text_1:mViewPager.setCurrentItem(0, false);break;case R.id.tab_text_2:mViewPager.setCurrentItem(1, false);break;case R.id.tab_text_3:mViewPager.setCurrentItem(2, false);break;case R.id.tab_text_4:mViewPager.setCurrentItem(3, false);break;}}private void setCurrentScroll(int selection) {if (mScroll1 != null && mScroll2 != null && mScroll3 != null&& mScroll4 != null) {mScroll1.setVisibility(selection == 0 ? View.VISIBLE: View.INVISIBLE);mScroll2.setVisibility(selection == 1 ? View.VISIBLE: View.INVISIBLE);mScroll3.setVisibility(selection == 2 ? View.VISIBLE: View.INVISIBLE);mScroll4.setVisibility(selection == 3 ? View.VISIBLE: View.INVISIBLE);}}@Overridepublic void onPageScrollStateChanged(int arg0) {Log.d("ActiontBar", "onPageScrollStateChanged");}@Overridepublic void onPageScrolled(int arg0, float arg1, int arg2) {Log.d("ActiontBar", "onPageScrolled");}@Overridepublic void onPageSelected(int arg0) {setCurrentScroll(arg0);Log.d("ActiontBar", "onPageSelected");}public class PagerAdapter extends FragmentPagerAdapter {PreferenceFragment[] fragments;String[] titles;public PagerAdapter(FragmentManager fm, Context context) {super(fm);fragments = new PreferenceFragment[4];fragments[0] = new PreferenceFragment(R.xml.settings_security);fragments[1] = new PreferenceFragment(R.xml.settings_delay);fragments[2] = new PreferenceFragment(R.xml.settings_others);fragments[3] = new PreferenceFragment(R.xml.settings_about);titles = new String[4];titles[0] = context.getString(R.string.security);titles[1] = context.getString(R.string.delay);titles[2] = context.getString(R.string.others);titles[3] = context.getString(R.string.about);}@Overridepublic Fragment getItem(int position) {return (Fragment) fragments[position];}@Overridepublic int getCount() {return fragments.length;}@Overridepublic String getPageTitle(int position) {return titles[position];}}
}
PreferenceFragment.java
public class PreferenceFragment extends ListFragment {private PreferenceManager mPreferenceManager;/*** The starting request code given out to preference framework.*/private static final int FIRST_REQUEST_CODE = 100;private static final int MSG_BIND_PREFERENCES = 0;private ListView lv;private int xmlId;private Handler mHandler = new Handler() {@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case MSG_BIND_PREFERENCES:bindPreferences();break;}}};// must be provided// public PreferenceFragment() {//// }public PreferenceFragment(int xmlId) {this.xmlId = xmlId;}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle b) {postBindPreferences();return lv;}@Overridepublic void onDestroyView() {super.onDestroyView();ViewParent p = lv.getParent();if (p != null) {((ViewGroup) p).removeView(lv);}}@Overridepublic void onCreate(Bundle b) {super.onCreate(b);if (b != null) {xmlId = b.getInt("xml");}mPreferenceManager = onCreatePreferenceManager();lv = (ListView) LayoutInflater.from(getActivity()).inflate(R.layout.preference_list_content, null);lv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);addPreferencesFromResource(xmlId);postBindPreferences();}@Overridepublic void onStop() {super.onStop();try {Method method = PreferenceManager.class.getDeclaredMethod("dispatchActivityStop");method.setAccessible(true);method.invoke(mPreferenceManager);} catch (Exception e) {e.printStackTrace();}}@Overridepublic void onDestroy() {super.onDestroy();lv = null;try {Method method = PreferenceManager.class.getDeclaredMethod("dispatchActivityDestroy");method.setAccessible(true);method.invoke(mPreferenceManager);} catch (Exception e) {e.printStackTrace();}}@Overridepublic void onSaveInstanceState(Bundle outState) {outState.putInt("xml", xmlId);super.onSaveInstanceState(outState);}@Overridepublic void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);try {Method method = PreferenceManager.class.getDeclaredMethod("dispatchActivityResult", int.class, int.class,Intent.class);method.setAccessible(true);method.invoke(mPreferenceManager, requestCode, resultCode, data);} catch (Exception e) {e.printStackTrace();}}/*** Posts a message to bind the preferences to the list view.* <p>* Binding late is preferred as any custom preference types created in* {@link #onCreate(Bundle)} are able to have their views recycled.*/private void postBindPreferences() {if (mHandler.hasMessages(MSG_BIND_PREFERENCES)) {return;}mHandler.obtainMessage(MSG_BIND_PREFERENCES).sendToTarget();}private void bindPreferences() {final PreferenceScreen preferenceScreen = getPreferenceScreen();if (preferenceScreen != null) {preferenceScreen.bind(lv);}}/*** Creates the {@link PreferenceManager}.* * @return The {@link PreferenceManager} used by this activity.*/private PreferenceManager onCreatePreferenceManager() {try {Constructor<PreferenceManager> c = PreferenceManager.class.getDeclaredConstructor(Activity.class, int.class);c.setAccessible(true);PreferenceManager preferenceManager = c.newInstance(this.getActivity(), FIRST_REQUEST_CODE);return preferenceManager;} catch (Exception e) {e.printStackTrace();return null;}}/*** Returns the {@link PreferenceManager} used by this activity.* * @return The {@link PreferenceManager}.*/public PreferenceManager getPreferenceManager() {return mPreferenceManager;}/*** Sets the root of the preference hierarchy that this activity is showing.* * @param preferenceScreen* The root {@link PreferenceScreen} of the preference hierarchy.*/public void setPreferenceScreen(PreferenceScreen preferenceScreen) {try {Method method = PreferenceManager.class.getDeclaredMethod("setPreferences", PreferenceScreen.class);method.setAccessible(true);boolean result = (Boolean) method.invoke(mPreferenceManager,preferenceScreen);if (result && preferenceScreen != null) {postBindPreferences();}} catch (Exception e) {e.printStackTrace();}}/*** Gets the root of the preference hierarchy that this activity is showing.* * @return The {@link PreferenceScreen} that is the root of the preference* hierarchy.*/public PreferenceScreen getPreferenceScreen() {try {Method method = PreferenceManager.class.getDeclaredMethod("getPreferenceScreen");method.setAccessible(true);return (PreferenceScreen) method.invoke(mPreferenceManager);} catch (Exception e) {e.printStackTrace();return null;}}/*** Adds preferences from activities that match the given {@link Intent}.* * @param intent* The {@link Intent} to query activities.*/public void addPreferencesFromIntent(Intent intent) {throw new RuntimeException("too lazy to include this bs");}/*** Inflates the given XML resource and adds the preference hierarchy to the* current preference hierarchy.* * @param preferencesResId* The XML resource ID to inflate.*/public void addPreferencesFromResource(int preferencesResId) {try {Method method = PreferenceManager.class.getDeclaredMethod("inflateFromResource", Context.class, int.class,PreferenceScreen.class);method.setAccessible(true);PreferenceScreen prefScreen = (PreferenceScreen) method.invoke(mPreferenceManager, getActivity(), preferencesResId,getPreferenceScreen());setPreferenceScreen(prefScreen);} catch (Exception e) {e.printStackTrace();}}/*** Finds a {@link Preference} based on its key.* * @param key* The key of the preference to retrieve.* @return The {@link Preference} with the key, or null.* @see PreferenceGroup#findPreference(CharSequence)*/public Preference findPreference(CharSequence key) {if (mPreferenceManager == null) {return null;}return mPreferenceManager.findPreference(key);}public interface OnPreferenceAttachedListener {public void onPreferenceAttached(PreferenceScreen root, int xmlId);}}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.ttdevs.actionbarandpreferencefragmentdemo"android:versionCode="1"android:versionName="1.0" ><uses-sdkandroid:minSdkVersion="15"android:targetSdkVersion="17" /><applicationandroid:allowBackup="true"android:icon="@drawable/ic_launcher"android:label="@string/app_name"android:theme="@android:style/Theme.DeviceDefault.Light" ><activityandroid:name=".MainActivity"android:label="@string/app_name"android:launchMode="singleTask" ><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>
其他配置文件略
2、效果图如下:
3、demo下载:
http://download.csdn.net/detail/ttdevs/5864875
这篇关于督促学习——ViewPager实现滑动的Preference页面且带ActionBar的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!