督促学习——ViewPager实现滑动的Preference页面且带ActionBar

2024-04-25 03:32

本文主要是介绍督促学习——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的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/933595

相关文章

MySQL双主搭建+keepalived高可用的实现

《MySQL双主搭建+keepalived高可用的实现》本文主要介绍了MySQL双主搭建+keepalived高可用的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,... 目录一、测试环境准备二、主从搭建1.创建复制用户2.创建复制关系3.开启复制,确认复制是否成功4.同

Java实现文件图片的预览和下载功能

《Java实现文件图片的预览和下载功能》这篇文章主要为大家详细介绍了如何使用Java实现文件图片的预览和下载功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... Java实现文件(图片)的预览和下载 @ApiOperation("访问文件") @GetMapping("

使用Sentinel自定义返回和实现区分来源方式

《使用Sentinel自定义返回和实现区分来源方式》:本文主要介绍使用Sentinel自定义返回和实现区分来源方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Sentinel自定义返回和实现区分来源1. 自定义错误返回2. 实现区分来源总结Sentinel自定

Java实现时间与字符串互相转换详解

《Java实现时间与字符串互相转换详解》这篇文章主要为大家详细介绍了Java中实现时间与字符串互相转换的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、日期格式化为字符串(一)使用预定义格式(二)自定义格式二、字符串解析为日期(一)解析ISO格式字符串(二)解析自定义

opencv图像处理之指纹验证的实现

《opencv图像处理之指纹验证的实现》本文主要介绍了opencv图像处理之指纹验证的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录一、简介二、具体案例实现1. 图像显示函数2. 指纹验证函数3. 主函数4、运行结果三、总结一、

Springboot处理跨域的实现方式(附Demo)

《Springboot处理跨域的实现方式(附Demo)》:本文主要介绍Springboot处理跨域的实现方式(附Demo),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不... 目录Springboot处理跨域的方式1. 基本知识2. @CrossOrigin3. 全局跨域设置4.

Spring Boot 3.4.3 基于 Spring WebFlux 实现 SSE 功能(代码示例)

《SpringBoot3.4.3基于SpringWebFlux实现SSE功能(代码示例)》SpringBoot3.4.3结合SpringWebFlux实现SSE功能,为实时数据推送提供... 目录1. SSE 简介1.1 什么是 SSE?1.2 SSE 的优点1.3 适用场景2. Spring WebFlu

基于SpringBoot实现文件秒传功能

《基于SpringBoot实现文件秒传功能》在开发Web应用时,文件上传是一个常见需求,然而,当用户需要上传大文件或相同文件多次时,会造成带宽浪费和服务器存储冗余,此时可以使用文件秒传技术通过识别重复... 目录前言文件秒传原理代码实现1. 创建项目基础结构2. 创建上传存储代码3. 创建Result类4.

SpringBoot日志配置SLF4J和Logback的方法实现

《SpringBoot日志配置SLF4J和Logback的方法实现》日志记录是不可或缺的一部分,本文主要介绍了SpringBoot日志配置SLF4J和Logback的方法实现,文中通过示例代码介绍的非... 目录一、前言二、案例一:初识日志三、案例二:使用Lombok输出日志四、案例三:配置Logback一

Python如何使用__slots__实现节省内存和性能优化

《Python如何使用__slots__实现节省内存和性能优化》你有想过,一个小小的__slots__能让你的Python类内存消耗直接减半吗,没错,今天咱们要聊的就是这个让人眼前一亮的技巧,感兴趣的... 目录背景:内存吃得满满的类__slots__:你的内存管理小助手举个大概的例子:看看效果如何?1.