使用Fragment仿微信之二Fragemnt使用及overflow菜单使用

来源:互联网 发布:api原油库存数据官网 编辑:程序博客网 时间:2024/05/17 09:43

本文使用代码非原创,特此声明

上文说到了仿微信app里面的ChangeColorIconWithTextView,接下来说说如何使用Fragment和溢出按钮的使用。

先看继承于Fragmen的TabFragment,它比较简单

public class TabFragment extends Fragment{private String mTitle = "Default";public TabFragment(){}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState){if (getArguments() != null){mTitle = getArguments().getString("title");}TextView textView = new TextView(getActivity());textView.setTextSize(20);textView.setBackgroundColor(Color.parseColor("#ffffffff"));textView.setGravity(Gravity.CENTER);textView.setText(mTitle);return textView;}}
在onCreateView中获取Bundle,并根据key值来获取String型的value,在该Fragment中构造一个TextView,并将这个value显示在其中。


再看MainActivity,先看其布局文件activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:zhy="http://schemas.android.com/apk/res/com.zhy.weixin6.ui"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <android.support.v4.view.ViewPager        android:id="@+id/id_viewpager"        android:layout_width="fill_parent"        android:layout_height="0dp"        android:layout_weight="1" >    </android.support.v4.view.ViewPager>    <LinearLayout        android:layout_width="fill_parent"        android:layout_height="60dp"        android:background="@drawable/tabbg"        android:orientation="horizontal" >        <com.zhy.weixin6.ui.ChangeColorIconWithTextView            android:id="@+id/id_indicator_one"            android:layout_width="0dp"            android:layout_height="fill_parent"            android:layout_weight="1"            android:padding="5dp"            zhy:icon="@drawable/ic_menu_start_conversation"            zhy:text="@string/tab_weixin"            zhy:text_size="12sp" />        <com.zhy.weixin6.ui.ChangeColorIconWithTextView            android:id="@+id/id_indicator_two"            android:layout_width="0dp"            android:layout_height="fill_parent"            android:layout_weight="1"            android:padding="5dp"            zhy:icon="@drawable/ic_menu_friendslist"            zhy:text="@string/tab_contact"            zhy:text_size="12sp" />        <com.zhy.weixin6.ui.ChangeColorIconWithTextView            android:id="@+id/id_indicator_three"            android:layout_width="0dp"            android:layout_height="fill_parent"            android:layout_weight="1"            android:padding="5dp"            zhy:icon="@drawable/ic_menu_emoticons"            zhy:text="@string/tab_find"            zhy:text_size="12sp" />        <com.zhy.weixin6.ui.ChangeColorIconWithTextView            android:id="@+id/id_indicator_four"            android:layout_width="0dp"            android:layout_height="fill_parent"            android:layout_weight="1"            android:padding="5dp"            zhy:icon="@drawable/ic_menu_allfriends"            zhy:text="@string/tab_me"            zhy:text_size="12sp" />    </LinearLayout></LinearLayout>
注意这里使用zhy时,需要添加命名空间xmlns:tools="http://schemas.android.com/tools",否则zhy无效

然后看0ncreate里面的内容

setOverflowShowingAlways();是为了在无论有menu键还是没有menu键的设备上都显示overflow按钮。什么是overflow呢?就是当菜单项过多时,将多余菜单项合并,在actionbar右角显示一个有三个灰色点的按钮。当然overflow按钮的图标也可以更改,其更改方法是在style中更改android:actionOverflowButtonStyle样式,如下

<resources>    <!--        Base application theme for API 11+. This theme completely replaces        AppBaseTheme from res/values/styles.xml on API 11+ devices.    -->    <style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">        <item name="android:actionOverflowButtonStyle">@style/WeChatActionButtonOverflow</item>    </style>    <style name="WeChatActionButtonOverflow" parent="android:style/Widget.Holo.ActionButton.Overflow">        <item name="android:src">@drawable/actionbar_add_icon</item>    </style></resources>

其他讲解均作为注释添加在代码里面。

详细代码

package com.zhy.weixin6.ui;import java.lang.reflect.Field;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.List;import android.annotation.SuppressLint;import android.os.Bundle;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentActivity;import android.support.v4.app.FragmentPagerAdapter;import android.support.v4.view.ViewPager;import android.support.v4.view.ViewPager.OnPageChangeListener;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.view.ViewConfiguration;import android.view.Window;import android.widget.Toast;@SuppressLint("NewApi")public class MainActivity extends FragmentActivity implementsOnPageChangeListener, OnClickListener{private ViewPager mViewPager;private List<Fragment> mTabs = new ArrayList<Fragment>();private FragmentPagerAdapter mAdapter;private String[] mTitles = new String[] { "First Fragment!","Second Fragment!", "Third Fragment!", "Fourth Fragment!" };private List<ChangeColorIconWithTextView> mTabIndicator = new ArrayList<ChangeColorIconWithTextView>();@Overrideprotected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);setOverflowShowingAlways();/** * 设置在actionbar是否显示图标,true为显示,false为不显示,注意这里的图标由当前activity的android:icon"属性来决定, * 当没有android:icon="@drawable/ic_launcher",则有当前application的android:icon属性来决定 */getActionBar().setDisplayShowHomeEnabled(false);mViewPager = (ViewPager) findViewById(R.id.id_viewpager);initDatas();mViewPager.setAdapter(mAdapter);mViewPager.setOnPageChangeListener(this);}private void initDatas(){        //添加TabFragment进listfor (String title : mTitles){TabFragment tabFragment = new TabFragment();Bundle args = new Bundle();args.putString("title", title);tabFragment.setArguments(args);mTabs.add(tabFragment);}//定义Fragment的适配器mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()){@Overridepublic int getCount(){return mTabs.size();}@Overridepublic Fragment getItem(int arg0){return mTabs.get(arg0);}};initTabIndicator();}@Overridepublic boolean onCreateOptionsMenu(Menu menu){getMenuInflater().inflate(R.menu.main, menu);return true;}//初始化ChangeColorIconWithTextView图标,并注册监听器private void initTabIndicator(){ChangeColorIconWithTextView one = (ChangeColorIconWithTextView) findViewById(R.id.id_indicator_one);ChangeColorIconWithTextView two = (ChangeColorIconWithTextView) findViewById(R.id.id_indicator_two);ChangeColorIconWithTextView three = (ChangeColorIconWithTextView) findViewById(R.id.id_indicator_three);ChangeColorIconWithTextView four = (ChangeColorIconWithTextView) findViewById(R.id.id_indicator_four);mTabIndicator.add(one);mTabIndicator.add(two);mTabIndicator.add(three);mTabIndicator.add(four);one.setOnClickListener(this);two.setOnClickListener(this);three.setOnClickListener(this);four.setOnClickListener(this);        //默认第一个icon为选中状态one.setIconAlpha(1.0f);}    /** * onPageSelected(int arg0) :   此方法是页面跳转完后得到调用,arg0是你当前选中的页面的Position(位置编号)。 */@Overridepublic void onPageSelected(int arg0){}    /** * onPageScrolled(int arg0,float arg1,int arg2),当页面在滑动的时候会调用此方法, * 在滑动被停止之前,此方法回一直得到调用。其中三个参数的含义分别为:      arg0 :当前页面,及你点击滑动的页面,      arg1:当前页面偏移的百分比,      arg2:当前页面偏移的像素位置    *  *  */@Overridepublic void onPageScrolled(int position, float positionOffset,int positionOffsetPixels){// Log.e("TAG", "position = " + position + " , positionOffset = "// + positionOffset);if (positionOffset > 0){ChangeColorIconWithTextView left = mTabIndicator.get(position);ChangeColorIconWithTextView right = mTabIndicator.get(position + 1);left.setIconAlpha(1 - positionOffset);right.setIconAlpha(positionOffset);}Toast.makeText(getApplicationContext(), "positionOffset为"+positionOffset, Toast.LENGTH_SHORT).show();}/** * 此方法是在状态改变的时候调用,其中arg0这个参数有三种状态(0,1,2)。arg0 ==1的时辰默示正在滑动, * arg0==2的时辰默示滑动完毕了,arg0==0的时辰默示什么都没做。     *当页面开始滑动的时候,三种状态的变化顺序为(1,2,0) */@Overridepublic void onPageScrollStateChanged(int state){}@Overridepublic void onClick(View v){resetOtherTabs();switch (v.getId()){case R.id.id_indicator_one:mTabIndicator.get(0).setIconAlpha(1.0f);mViewPager.setCurrentItem(0, false);break;case R.id.id_indicator_two:mTabIndicator.get(1).setIconAlpha(1.0f);//设置为true时,跳转无动画mViewPager.setCurrentItem(1, false);//设置为true时,有动画//mViewPager.setCurrentItem(1, true);break;case R.id.id_indicator_three:mTabIndicator.get(2).setIconAlpha(1.0f);mViewPager.setCurrentItem(2, false);break;case R.id.id_indicator_four:mTabIndicator.get(3).setIconAlpha(1.0f);mViewPager.setCurrentItem(3, false);break;}}/** * 重置其他的Tab,使它们变成非选中状态 */private void resetOtherTabs(){for (int i = 0; i < mTabIndicator.size(); i++){mTabIndicator.get(i).setIconAlpha(0);}}    /** * 当按下物理menu键按下overflow按钮时便会触发该函数 */@Overridepublic boolean onMenuOpened(int featureId, Menu menu){if (featureId == Window.FEATURE_ACTION_BAR && menu != null){if (menu.getClass().getSimpleName().equals("MenuBuilder")){try{//根据私有属性setOptionalIconsVisible获得MethodMethod m = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);//将属性设为可访问的m.setAccessible(true);//使用以下语句则会在溢出菜单中显示图标和文字,系统默认不显示图标m.invoke(menu, true);//使用以下语句则会在溢出菜单中不显示图标,仅显示文字,系统默认不显示图标//m.invoke(menu, false);} catch (Exception e){}}}return super.onMenuOpened(featureId, menu);}    /**     * 设置overflow按钮一直显示     */private void setOverflowShowingAlways(){try{// true if a permanent menu key is present, false otherwise.ViewConfiguration config = ViewConfiguration.get(this);//使用java反射技术,获取getDeclaredField类的私有属性sHasPermanentMenuKey Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");//将属性设为可访问的menuKeyField.setAccessible(true);//为属性赋值为falsemenuKeyField.setBoolean(config, false);//menuKeyField.setBoolean(config, true);} catch (Exception e){e.printStackTrace();}}}

水平有限,有不足或错误之处请大家指出并谅解!




0 0
原创粉丝点击