由于TabActivity在Android4.0以后已经被完全弃用,那么我就不再浪费口水继续讲解它了,取而代之的是Fragment。Fragment是Android3.0新增的概念,Fragment翻译成中文是碎片的意思,不过却和Activity十分的相似,这一篇我花大量的篇幅来详细的讲解Fragment的介绍和使用方法。
一、Fragment的基础知识介绍
1.1概述
1.1.1 特性
Fragment是activity的界面中的一部分或一种行为。可以把多个Fragment组合到一个activity中来创建一个多界面
并且可以在多个activity中重用一个Fragment。可以把Fragment任务模块化的一段activity,它具有自己的生命周期,
接收它自己的事件,并可以在activity运行时被添加或删除。
Fragment不能独立存在,它必须嵌入到activity中,而且Fragment的生命周期直接受所在的activity的影响。例
如:当activity暂停时,他拥有的所有的Fragment都暂停了,当activity销毁时,他拥有的所有Fragment都被销毁。然
而,当activity运行时(在onResume()之后,onPause()之前),可以单独地操作每个Fragment,比如添加或删除它
们。当中执行上述针对Fragment的事务时,可以将事务添加到一个栈中,这个栈被activity管理,栈中的每一条都是一
个Fragment的一次事务。有了这个栈,就可以反向执行Fragment的事务,这样就可以在Fragment级支持“返回”键
(向后导航)。
当向activity中添加一个Fragment时,它须置于ViewGroup控件中,并且需定义Fragment自己的界面。可以在
layout.xml布局文件中声明Fragment,元素为:
ViewGroup控件中。然而,Fragment不一定非要放在activity的界面中,它可以隐藏在后台为activity工作。
1.1.2 生命周期
onCreate():
当创建fragment时系统调用此方法。在其中必须初始化fragment的基础组件们。可参考activity的说明;
onCreateView():
系统在fragment要画自己的界面时调用(在真正显示之前)此方法,这个方法必须返回fragment的layout的根控
件,如果这个fragment不提供界面,那它应返回null;
onPause():
大多数程序应最少对fragment实现这三个方法,当然还有其它几个回调方法可应该按情况实现之,所有的声明周期
回调函数在“操控fragment的生命周期”一节中有详细讨论。
下图为fragment的生命周期(它所在的activity处于运行状态)
Activity和Fragment生命周期对比图如下:
两个的生命周期很类似,也息息相关。
1.1.3 派生类
DialogFragment
显示一个浮动的对话框。使用这个类创建对话框是替代activity创建对话框的最佳选择。因为可以把fragmentdialog
放入到activity的返回栈中,使用户能再返回到这个对话框。
ListFragment
显示一个列表控件,就像ListActivity类,它提供了很多管理列表的方法,比如onListItemClick()方法响应click事件。
PreferenceFragment
显示一个由Preference对象组成的列表,与PreferenceActivity相同。它用于为程序创建“设置”activity。
1.2 范例
写一个读新闻的程序,可以用一个fragment显示标题列表,另一个fragment显示选中标题的内容,这两个fragment
都在一个activity上,并排显示。那么这两个fragment都有自己的生命周期并响应自己感兴趣的事件。于是,不需要再
像手机上那样用一个activity显示标题列表,用另一个activity显示新闻内容;现在可以把两者放在一个activity上同时显
示出来。如下图:
Fragment必须被写成可重用的模块。因为fragment有自己的layout,自己进行事件响应,拥有自己的生命周期和
行为,所以可以在多个activity中包含同一个Fragment的不同实例。这对于让世界在不同的屏幕尺寸下都能给用户完美
的体验尤其重要。比如可以在程序运行于大屏幕中时启动包含很多fragment的activity,而在运行小屏幕时启动一个包
含少量fragment的activity。
刚才读新闻的程序,当检测到程序运行于大屏幕时,启动activityA,将标题列表和新闻内容这两个fragment都放
在activityA中;当检测到程序运行于小屏幕时,还是启动activityA,但此时A中只有标题列表fragment,当选中一个标
题时,activityA启动activityB,B中含有新闻内容fragment。
1.3 创建Fragment
要创建fragment,必须从Fragment或Fragment的派生类派生出一个类。Fragment的代码写起来有些像activity。
它具有跟activity一样的回调方法,比如onCreate(),onStart(),onPause()和onStop()。实际上,如果想把老的程序改为
使用fragment,基本上只需要把activity的回调方法的代码移到fragment中对应的方法即可。
1.3.1添加有界面的Fragment
Fragment一般作为activity的用户界面的一部分,把它自己layout嵌入到activity的layout中。一个要为fragment提
供layout,必须实现onCreateView()回调方法,然后在这个方法中返回一个View对象,这个对象时fragment的layout的
根。
注意:如果fragment是从ListFragment中派生的,就不需要实现onCreateView()方法了,因为默认的实现已经返
回了ListView控件对象。
要从onCreateView()方法中返回layout对象,可以从layout.xml布局文件中生成layout对象。为了帮助这样做,
onCreateView()提供了一个layoutInflater对象。举例:以下代码展示了一个Fragment的子类如何从layout.xml布局文件
example_fragment.xml中生成对象。
public static ExampleFragment extends Fragment {
@Override
publicView onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
returninflater.inflate(R.layout.example_fragment, container, false);
}
}
方法一:在activity的layout.xml文件中声明fragment
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//创建一个fragment
Fragment newFragment = new ExampleFragment();
//实例化fragment事务管理器
FragmentTransaction transaction = getFragmentManager().beginTransaction();
//用新创建的fragment来代替fragment_container
transaction.replace(R.id.fragment_container,newFragment);
//添加进栈中
transaction.addToBackStack(null);
//提交事务
transaction.commit();
package co.cm.fragement;
import co.cm.fragement.R;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
public class AndroidFragmentActivity extends Activity {
// 主activity
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WifiAdmin.getWifiAdmin().setmContext(AndroidFragmentActivity.this);
WifiAdmin.getWifiAdmin().getWifiMeathod();
}
}
package co.cm.fragement;
import co.cm.fragement.R;
import android.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ToggleButton;
/**
* @author yuyang
* 功能描述:左面fragment界面类,该类提供了选项操作
*/
public class FragementList extends Fragment {
//点击切换到wifi存储界面
private TextView wifi;
//点击切换到save存储界面
private TextView saveBut;
//定义右面fragment实例
private FragementDetails frag_detail;
//打开关闭wifi按钮
private ToggleButton toggleButton;
//toggleButton按钮是否被点击
private boolean isChecked = false;
//监听button状态线程标志位
private boolean butIsRunning = false;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// 在这里初始化fragment的页面
return inflater.inflate(R.layout.frag_list, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// 由于fragment不是activity,不是oncreated,而是onActivityCreated
setView();
setListener();
startThread();// 启动控制button的线程,当wifi状态不是在1或者3的时候,不可点击,
// if (frag != null && frag.isInLayout()) {
// switch (arg2) {
// case 0:
// frag.setText("0000");
}
/**
* 给按钮设置监听
*/
public void setListener() {
saveBut.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
frag_detail.setSaveShow();
}
});
wifi.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
frag_detail.setWifiShow();
Log.i("111", WifiAdmin.getWifiAdmin().checkState() + "===-=-");
checktoggleButton();// 当点回到wifi界面时,刷新button的状态
}
});
toggleButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.i("111", isChecked + "/" + WifiAdmin.getWifiAdmin().checkState());
if (isChecked) {
WifiAdmin.getWifiAdmin().OpenWifi();
frag_detail.setWifiShow();
// toggleButton.setText("关闭");
toggleButton.setChecked(false);
isChecked = false;
} else {
WifiAdmin.getWifiAdmin().CloseWife();
frag_detail.setWifiShow();
// toggleButton.setText("打开");
toggleButton.setChecked(true);
isChecked = true;
}
toggleButton.setClickable(false);
}
});
}
//
public void checktoggleButton() {
if (WifiAdmin.getWifiAdmin().checkState() == 1) {
toggleButton.setChecked(true);
isChecked = true;
}
if (WifiAdmin.getWifiAdmin().checkState() == 3) {
toggleButton.setChecked(false);
isChecked = false;
}
}
public void setView() {
wifi = (TextView) getView().findViewById(R.id.wifi);
toggleButton = (ToggleButton) getView().findViewById(R.id.toggleButton);
saveBut = (TextView) getView().findViewById(R.id.saveBut);
// 实例化右面界面,以便操纵里面的方法F
frag_detail = (FragementDetails) getFragmentManager().findFragmentById(R.id.frag_detail);
// 初始化button的装态
if (WifiAdmin.getWifiAdmin().checkState() == 3) {
toggleButton.setChecked(false);
isChecked = false;
}
if (WifiAdmin.getWifiAdmin().checkState() == 1) {
toggleButton.setChecked(true);
isChecked = true;
}
toggleButton.setClickable(true);
}
@Override
public void onDestroy() {
frag_detail.stopWifiThread();
butIsRunning = false;
super.onDestroy();
}
private void startThread() {
butIsRunning = true;
new Thread(new Runnable() {
@Override
public void run() {
while (butIsRunning) {
//只有wifi状态改变变化完毕之后才能允许点击按钮
if (WifiAdmin.getWifiAdmin().checkState() == 3) {
if (!isChecked) {
toggleButton.setClickable(true);
}
} else if (WifiAdmin.getWifiAdmin().checkState() == 1) {
if (isChecked) {
toggleButton.setClickable(true);
}
}
}
}
}).start();
}
}
package co.cm.fragement;
import java.util.ArrayList;
import java.util.List;
import co.cm.fragement.R;
import android.app.Fragment;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* @author yangyu
* 功能描述:右面fragment界面类,该类实现了右面显示的操作
*/
public class FragementDetails extends Fragment {
private TextView mac_address, bssid, ip_address, id, info, wifiText;
private ListView listView;
private LinearLayout wifiLinear;
private RelativeLayout save, wifi;
private boolean ThreadFlag = false;
//wifi数据适配器
private WifiAdapter wifiAdapter;
// 扫描出的网络连接列表
private List mWifiList = new ArrayList();
// 网络连接列表
private List mWifiConfiguration = null;
private int nowWifiState = 0;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
return inflater.inflate(R.layout.frag_detail, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setView();
// setListener();
setWifiShow();
}
/**
* 显示wifi界面
*/
public void setWifiShow() {
//通过隐藏显示来达到不同页面内容的切换
save.setVisibility(View.GONE);
wifi.setVisibility(View.VISIBLE);
stopWifiThread();
refreshWifi();
}
/**
* 显示保存界面
*/
public void setSaveShow() {
stopWifiThread();
save.setVisibility(View.VISIBLE);
wifi.setVisibility(View.GONE);
}
/**
* 初始化组件
*/
public void setView() {
// -----------------wifi-----------------
wifiText = (TextView) getView().findViewById(R.id.wifiText);
mac_address = (TextView) getView().findViewById(R.id.mac_address);
bssid = (TextView) getView().findViewById(R.id.bssid);
ip_address = (TextView) getView().findViewById(R.id.ip_address);
id = (TextView) getView().findViewById(R.id.id);
info = (TextView) getView().findViewById(R.id.info);
listView = (ListView) getView().findViewById(R.id.listview);
wifiLinear = (LinearLayout) getView().findViewById(R.id.wifiLinear);
save = (RelativeLayout) getView().findViewById(R.id.save);
wifi = (RelativeLayout) getView().findViewById(R.id.wifi);
wifiAdapter = new WifiAdapter();
listView.setAdapter(wifiAdapter);
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
nowWifiState = WifiAdmin.getWifiAdmin().checkState();
// 当wifi打开时,刷新wifi列表的内容
if (nowWifiState == 3) {
mWifiList = WifiAdmin.getWifiAdmin().GetWifiList();
// 如果刚开始检测的wifi列表为空,则创建一个实例化的wifi而不是null,负责会在adpter里面报错
if (mWifiList != null) {
// 如果wifi列表发生改变,则更新,else不更新
if (!mWifiList.toString().equals(
WifiAdmin.getWifiAdmin().getLastWifiList().toString())) {
WifiAdmin.getWifiAdmin().setLastWifiList(mWifiList);
wifiAdapter.notifyDate();
}
} else {
mWifiList = new ArrayList();
}
}
refreshMeathod();
super.handleMessage(msg);
}
};
/**
* 刷新wifi的状态
*/
public void refreshWifi() {
new Thread(new Runnable() {
@Override
public void run() {
ThreadFlag = true;
while (ThreadFlag) {
// Log.i("111", WifiAdmin.getWifiAdmin().checkState() +
// "!!!");
Message msg = handler.obtainMessage();
handler.sendMessage(msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
public void refreshMeathod() {
// 此处可用switch
if (nowWifiState == 3) {
wifiLinear.setVisibility(View.VISIBLE);
wifiText.setVisibility(View.INVISIBLE);
mac_address.setText(WifiAdmin.getWifiAdmin().GetMacAddress() + "");
bssid.setText(WifiAdmin.getWifiAdmin().GetBSSID() + "");
ip_address.setText(WifiAdmin.getWifiAdmin().GetIPAddress() + "");
id.setText(WifiAdmin.getWifiAdmin().GetNetworkId() + "");
info.setText(WifiAdmin.getWifiAdmin().GetWifiInfo() + "");
} else if (nowWifiState == 1) {
wifiText.setVisibility(View.VISIBLE);
wifiLinear.setVisibility(View.INVISIBLE);
wifiText.setText("要查看可用的网络,请打开wifi");
} else if (nowWifiState == 2) {
wifiText.setVisibility(View.VISIBLE);
wifiLinear.setVisibility(View.INVISIBLE);
wifiText.setText("wifi正在打开");
} else if (nowWifiState == 4) {
wifiText.setVisibility(View.VISIBLE);
wifiLinear.setVisibility(View.INVISIBLE);
wifiText.setText("wifi正在关闭");
} else {
wifiText.setVisibility(View.VISIBLE);
wifiLinear.setVisibility(View.INVISIBLE);
wifiText.setText("我不知道wifi正在做什么");
}
}
public void stopWifiThread() {
ThreadFlag = false;
}
public class WifiAdapter extends BaseAdapter {
@Override
public int getCount() {
return mWifiList.size();
}
@Override
public Object getItem(int position) {
return mWifiList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
final ChatViewHolder vh;
if (convertView == null) {
vh = new ChatViewHolder();
view = View.inflate(WifiAdmin.getWifiAdmin().getmContext(),
R.layout.wifi_list, null);
vh.wifi_name = (TextView) view.findViewById(R.id.wifi_name);
vh.wifi_name_state = (TextView) view
.findViewById(R.id.wifi_name_state);
view.setTag(vh);
} else {
vh = (ChatViewHolder) view.getTag();
}
vh.wifi_name.setText(mWifiList.get(position).SSID.toString());// 网络的名字,唯一区别WIFI网络的名字
vh.wifi_name_state.setText(mWifiList.get(position).level + "");
return view;
}
public void notifyDate() {
notifyDataSetChanged();
}
}
public class ChatViewHolder {
TextView wifi_name;// 网络的名字,唯一区别WIFI网络的名字
TextView wifi_name_state;// 所发现的WIFI网络信号强度
}
}
package co.cm.fragement;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.util.Log;
/**
* @author yangyu
* wifiAdmin提供了wifi操作的方法
*/
public class WifiAdmin {
private static WifiAdmin wifiAdmin;
private WifiManager mWifiManager = null;
private WifiInfo mWifiInfo = null;
// 扫描出的网络连接列表
private List mWifiList = new ArrayList();
// 扫描出的网络连接列表
private List lastWifiList = new ArrayList();
// 网络连接列表
private List mWifiConfiguration = null;
private WifiLock mWifiLock = null;
// 上次网络状态
private int lastWifiState = 0;
//定义上下文Context
Context mContext;
public List getLastWifiList() {
return lastWifiList;
}
public void setLastWifiList(List lastWifiList) {
this.lastWifiList = lastWifiList;
}
public int getLastWifiState() {
return lastWifiState;
}
public void setLastWifiState(int lastWifiState) {
this.lastWifiState = lastWifiState;
}
public static WifiAdmin getWifi() {
return wifiAdmin;
}
public Context getmContext() {
return mContext;
}
public void setmContext(Context mContext) {
this.mContext = mContext;
}
public static WifiAdmin getWifiAdmin() {
if (wifiAdmin == null) {
wifiAdmin = new WifiAdmin();
}
return wifiAdmin;
}
public void getWifiMeathod() {
mWifiManager = (WifiManager) mContext
.getSystemService(mContext.WIFI_SERVICE);
mWifiInfo = mWifiManager.getConnectionInfo();
}
/**
* 打开wifi
*/
public void OpenWifi() {
if (!mWifiManager.isWifiEnabled()) {
mWifiManager.setWifiEnabled(true);
} else {
Log.i("111", "open 失败");
}
}
/**
* 关闭wifi
*/
public void CloseWife() {
if (mWifiManager.isWifiEnabled()) {
mWifiManager.setWifiEnabled(false);
} else {
Log.i("111", "close 失败");
}
}
/**
* 锁定wifi
*/
public void lockWifi() {
mWifiLock.acquire();
}
public void rlockWifi() {
if (mWifiLock.isHeld()) {
mWifiLock.acquire();
}
}
// 检查当前wifi状态WIFI网卡的状态是由一系列的整形常量来表示的。
//1.WIFI_STATE_DISABLED : WIFI网卡不可用(1)
//2.WIFI_STATE_DISABLING : WIFI网卡正在关闭(0)
//3.WIFI_STATE_ENABLED : WIFI网卡可用(3)
//4.WIFI_STATE_ENABLING : WIFI网正在打开(2) (WIFI启动需要一段时间)
//5.WIFI_STATE_UNKNOWN : 未知网卡状态
public int checkState() {
return mWifiManager.getWifiState();
}
/**
* 创建一个wifilock
*/
public void Createwifilock() {
mWifiLock = mWifiManager.createWifiLock("Testss");
}
/**
* 得到配置好的网络
* @return
*/
public List GetConfinguration() {
return mWifiConfiguration;
}
/**
* 连接配置好的指定ID的网络
* @param index
*/
public void ConnectConfiguration(int index) {
if (index > mWifiConfiguration.size()) {
return;
}
mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId,true);
}
/**
* 开始扫描网络
*/
public void StartScan() {
mWifiManager.startScan();
// 得到扫描结果
mWifiList = mWifiManager.getScanResults();
// 得到配置好的网络连接
mWifiConfiguration = mWifiManager.getConfiguredNetworks();
}
/**
* 得到网络列表
* @return
*/
public List GetWifiList() {
mWifiManager.startScan();
// 得到扫描结果
mWifiList = mWifiManager.getScanResults();
return mWifiList;
}
public List getmWifiConfiguration() {
return mWifiConfiguration;
}
/**
* 查看扫描结果
*/
public StringBuilder LookUpScan() {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < mWifiList.size(); i++) {
stringBuilder.append("Index_" + new Integer(i + 1).toString() + ":");
// 将ScanResult信息转换成一个字符串包
// 其中把包括:BSSID、SSID、capabilities、frequency、level
stringBuilder.append((mWifiList.get(i)).toString());
stringBuilder.append("\n");
}
return stringBuilder;
}
/**
* 得到MAC地址
*/
public String GetMacAddress() {
return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress();
}
/**
* 得到接入点的BSSID
*/
public String GetBSSID() {
return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID();
}
/**
* 得到IP地址
*/
public int GetIPAddress() {
return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress();
}
/**
* 得到连接的ID
*/
public int GetNetworkId() {
return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId();
}
/**
* 得到WifiInfo的所有信息包
*/
public String GetWifiInfo() {
return (mWifiInfo == null) ? "NULL" : mWifiInfo.toString();
}
/**
* 添加一个网络并连接
*/
public void AddNetwork(WifiConfiguration wcg) {
int wcgID = mWifiManager.addNetwork(wcg);
mWifiManager.enableNetwork(wcgID, true);
}
/**
* 断开指定ID的网络
*/
public void DisconnectWifi(int netId) {
mWifiManager.disableNetwork(netId);
mWifiManager.disconnect();
}
}
package com.eoe.tampletfragment.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.eoe.tampletfragment.R;
/**
* @author yangyu
* 功能描述:自定义顶部工具栏
*/
public class TitleView extends FrameLayout implements View.OnClickListener {
private Button mLeftBtn;
private Button mRightBtn;
private TextView mTitle;
private OnLeftButtonClickListener mOnLeftButtonClickListener;
private OnRightButtonClickListener mOnRightButtonClickListener;
public interface OnLeftButtonClickListener {
public void onClick(View button);
}
public interface OnRightButtonClickListener {
public void onClick(View button);
}
public void setLeftButton(String text, OnLeftButtonClickListener listener) {
mLeftBtn.setText(text);
mLeftBtn.setVisibility(View.VISIBLE);
mOnLeftButtonClickListener = listener;
}
public void setLeftButton(int stringID, OnLeftButtonClickListener listener) {
mLeftBtn.setText(stringID);
mLeftBtn.setVisibility(View.VISIBLE);
mOnLeftButtonClickListener = listener;
}
public void removeLeftButton() {
mLeftBtn.setText("");
mLeftBtn.setVisibility(View.INVISIBLE);
mOnLeftButtonClickListener = null;
}
public void hiddenLeftButton() {
mLeftBtn.setVisibility(View.INVISIBLE);
}
public void showLeftButton() {
mLeftBtn.setVisibility(View.VISIBLE);
}
public void setRightButton(String text, OnRightButtonClickListener listener) {
mRightBtn.setText(text);
mRightBtn.setVisibility(View.VISIBLE);
mOnRightButtonClickListener = listener;
}
public void setRightButton(int stringID, OnRightButtonClickListener listener) {
mRightBtn.setText(stringID);
mRightBtn.setVisibility(View.VISIBLE);
mOnRightButtonClickListener = listener;
}
public void removeRightButton() {
mRightBtn.setText("");
mRightBtn.setVisibility(View.INVISIBLE);
mOnRightButtonClickListener = null;
}
public void hiddenRightButton() {
mRightBtn.setVisibility(View.INVISIBLE);
}
public void showRightButton() {
mRightBtn.setVisibility(View.VISIBLE);
}
public TitleView(Context context) {
this(context, null);
}
public TitleView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public TitleView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.title_view, this, true);
mLeftBtn = (Button) findViewById(R.id.left_btn);
mLeftBtn.setVisibility(View.INVISIBLE);
mLeftBtn.setOnClickListener(this);
mRightBtn = (Button) findViewById(R.id.right_btn);
mRightBtn.setVisibility(View.INVISIBLE);
mRightBtn.setOnClickListener(this);
mTitle = (TextView) findViewById(R.id.title_text);
mTitle.setVisibility(View.INVISIBLE);
}
public void setTitle(String text) {
mTitle.setVisibility(View.VISIBLE);
mTitle.setText(text);
}
public void setTitle(int stringID) {
mTitle.setVisibility(View.VISIBLE);
mTitle.setText(stringID);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.left_btn:
if(mOnLeftButtonClickListener != null)
mOnLeftButtonClickListener.onClick(v);
break;
case R.id.right_btn:
if(mOnRightButtonClickListener != null)
mOnRightButtonClickListener.onClick(v);
break;
}
}
}
package com.eoe.tampletfragment.fragment;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.eoe.tampletfragment.R;
/**
* @author yangyu
* 功能描述:自定义底部工具栏
*/
public class FragmentIndicator extends LinearLayout implements OnClickListener {
private int mDefaultIndicator = 0;
private static int mCurIndicator;
private static View[] mIndicators;
private OnIndicateListener mOnIndicateListener;
private static final String TAG_ICON_0 = "icon_tag_0";
private static final String TAG_ICON_1 = "icon_tag_1";
private static final String TAG_ICON_2 = "icon_tag_2";
private static final String TAG_TEXT_0 = "text_tag_0";
private static final String TAG_TEXT_1 = "text_tag_1";
private static final String TAG_TEXT_2 = "text_tag_2";
private static final int COLOR_UNSELECT = Color.argb(100, 0xff, 0xff, 0xff);
private static final int COLOR_SELECT = Color.WHITE;
private FragmentIndicator(Context context) {
super(context);
}
public FragmentIndicator(Context context, AttributeSet attrs) {
super(context, attrs);
mCurIndicator = mDefaultIndicator;
setOrientation(LinearLayout.HORIZONTAL);
init();
}
private View createIndicator(int iconResID, int stringResID, int stringColor,
String iconTag, String textTag) {
LinearLayout view = new LinearLayout(getContext());
view.setOrientation(LinearLayout.VERTICAL);
view.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1));
view.setGravity(Gravity.CENTER_HORIZONTAL);
ImageView iconView = new ImageView(getContext());
iconView.setTag(iconTag);
iconView.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1));
iconView.setImageResource(iconResID);
TextView textView = new TextView(getContext());
textView.setTag(textTag);
textView.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1));
textView.setTextColor(stringColor);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
textView.setText(stringResID);
view.addView(iconView);
view.addView(textView);
return view;
}
private void init() {
mIndicators = new View[3];
mIndicators[0] = createIndicator(R.drawable.ic_home_focused,
R.string.tab_home, COLOR_SELECT, TAG_ICON_0, TAG_TEXT_0);
mIndicators[0].setBackgroundResource(R.drawable.indic_select);
mIndicators[0].setTag(Integer.valueOf(0));
mIndicators[0].setOnClickListener(this);
addView(mIndicators[0]);
mIndicators[1] = createIndicator(R.drawable.ic_search_normal,
R.string.tab_search, COLOR_UNSELECT, TAG_ICON_1, TAG_TEXT_1);
mIndicators[1].setBackgroundColor(Color.alpha(0));
mIndicators[1].setTag(Integer.valueOf(1));
mIndicators[1].setOnClickListener(this);
addView(mIndicators[1]);
mIndicators[2] = createIndicator(R.drawable.ic_settings_normal,
R.string.tab_settings, COLOR_UNSELECT, TAG_ICON_2, TAG_TEXT_2);
mIndicators[2].setBackgroundColor(Color.alpha(0));
mIndicators[2].setTag(Integer.valueOf(2));
mIndicators[2].setOnClickListener(this);
addView(mIndicators[2]);
}
public static void setIndicator(int which) {
// clear previous status.
mIndicators[mCurIndicator].setBackgroundColor(Color.alpha(0));
ImageView prevIcon;
TextView prevText;
switch(mCurIndicator) {
case 0:
prevIcon =(ImageView) mIndicators[mCurIndicator].findViewWithTag(TAG_ICON_0);
prevIcon.setImageResource(R.drawable.ic_home_normal);
prevText = (TextView) mIndicators[mCurIndicator].findViewWithTag(TAG_TEXT_0);
prevText.setTextColor(COLOR_UNSELECT);
break;
case 1:
prevIcon =(ImageView) mIndicators[mCurIndicator].findViewWithTag(TAG_ICON_1);
prevIcon.setImageResource(R.drawable.ic_search_normal);
prevText = (TextView) mIndicators[mCurIndicator].findViewWithTag(TAG_TEXT_1);
prevText.setTextColor(COLOR_UNSELECT);
break;
case 2:
prevIcon =(ImageView) mIndicators[mCurIndicator].findViewWithTag(TAG_ICON_2);
prevIcon.setImageResource(R.drawable.ic_settings_normal);
prevText = (TextView) mIndicators[mCurIndicator].findViewWithTag(TAG_TEXT_2);
prevText.setTextColor(COLOR_UNSELECT);
break;
}
// update current status.
mIndicators[which].setBackgroundResource(R.drawable.indic_select);
ImageView currIcon;
TextView currText;
switch(which) {
case 0:
currIcon =(ImageView) mIndicators[which].findViewWithTag(TAG_ICON_0);
currIcon.setImageResource(R.drawable.ic_home_focused);
currText = (TextView) mIndicators[which].findViewWithTag(TAG_TEXT_0);
currText.setTextColor(COLOR_SELECT);
break;
case 1:
currIcon =(ImageView) mIndicators[which].findViewWithTag(TAG_ICON_1);
currIcon.setImageResource(R.drawable.ic_search_focused);
currText = (TextView) mIndicators[which].findViewWithTag(TAG_TEXT_1);
currText.setTextColor(COLOR_SELECT);
break;
case 2:
currIcon =(ImageView) mIndicators[which].findViewWithTag(TAG_ICON_2);
currIcon.setImageResource(R.drawable.ic_settings_focused);
currText = (TextView) mIndicators[which].findViewWithTag(TAG_TEXT_2);
currText.setTextColor(COLOR_SELECT);
break;
}
mCurIndicator = which;
}
public interface OnIndicateListener {
public void onIndicate(View v, int which);
}
public void setOnIndicateListener(OnIndicateListener listener) {
mOnIndicateListener = listener;
}
@Override
public void onClick(View v) {
if (mOnIndicateListener != null) {
int tag = (Integer) v.getTag();
switch (tag) {
case 0:
if (mCurIndicator != 0) {
mOnIndicateListener.onIndicate(v, 0);
setIndicator(0);
}
break;
case 1:
if (mCurIndicator != 1) {
mOnIndicateListener.onIndicate(v, 1);
setIndicator(1);
}
break;
case 2:
if (mCurIndicator != 2) {
mOnIndicateListener.onIndicate(v, 2);
setIndicator(2);
}
break;
default:
break;
}
}
}
}
package com.eoe.tampletfragment.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.eoe.tampletfragment.HelpActivity;
import com.eoe.tampletfragment.R;
import com.eoe.tampletfragment.view.TitleView;
import com.eoe.tampletfragment.view.TitleView.OnLeftButtonClickListener;
import com.eoe.tampletfragment.view.TitleView.OnRightButtonClickListener;
/**
* @author yangyu
* 功能描述:首页fragment页面
*/
public class HomeFragment extends Fragment {
private View mParent;
private FragmentActivity mActivity;
private TitleView mTitle;
private TextView mText;
/**
* Create a new instance of DetailsFragment, initialized to show the text at
* 'index'.
*/
public static HomeFragment newInstance(int index) {
HomeFragment f = new HomeFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
public int getShownIndex() {
return getArguments().getInt("index", 0);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mActivity = getActivity();
mParent = getView();
mTitle = (TitleView) mParent.findViewById(R.id.title);
mTitle.setTitle(R.string.title_home);
mTitle.setLeftButton(R.string.exit, new OnLeftButtonClickListener(){
@Override
public void onClick(View button) {
mActivity.finish();
}
});
mTitle.setRightButton(R.string.help, new OnRightButtonClickListener() {
@Override
public void onClick(View button) {
goHelpActivity();
}
});
mText = (TextView) mParent.findViewById(R.id.fragment_home_text);
}
private void goHelpActivity() {
Intent intent = new Intent(mActivity, HelpActivity.class);
startActivity(intent);
}
@Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
package com.eoe.tampletfragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Window;
/**
* @author yangyu
* 功能描述:帮助Activity界面
*/
public class HelpActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_help);
}
}
package com.eoe.tampletfragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.Window;
import com.eoe.tampletfragment.fragment.FragmentIndicator;
import com.eoe.tampletfragment.fragment.FragmentIndicator.OnIndicateListener;
/**
* @author yangyu
* 功能描述:主Activity类,继承自FragmentActivity
*/
public class MainActivity extends FragmentActivity {
public static Fragment[] mFragments;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
setFragmentIndicator(0);
}
/**
* 初始化fragment
*/
private void setFragmentIndicator(int whichIsDefault) {
mFragments = new Fragment[3];
mFragments[0] = getSupportFragmentManager().findFragmentById(R.id.fragment_home);
mFragments[1] = getSupportFragmentManager().findFragmentById(R.id.fragment_search);
mFragments[2] = getSupportFragmentManager().findFragmentById(R.id.fragment_settings);
getSupportFragmentManager().beginTransaction().hide(mFragments[0])
.hide(mFragments[1]).hide(mFragments[2]).show(mFragments[whichIsDefault]).commit();
FragmentIndicator mIndicator = (FragmentIndicator) findViewById(R.id.indicator);
FragmentIndicator.setIndicator(whichIsDefault);
mIndicator.setOnIndicateListener(new OnIndicateListener() {
@Override
public void onIndicate(View v, int which) {
getSupportFragmentManager().beginTransaction()
.hide(mFragments[0]).hide(mFragments[1])
.hide(mFragments[2]).show(mFragments[which]).commit();
}
});
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
}