之前将Fragment页面的加载都写在HomeFrament中,现在进行优化,页面的显示和数据的加载都统一初始化,创建2个abstract方法,一个是加载数据的返回值,一个是显示加载成功的界面,这两个都需要单独写
BaseFragment.java
package com.ldw.market.fragment;
import com.ldw.market.R;
import com.ldw.market.utils.ViewUtils;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
public abstract class BaseFragment extends Fragment {
//初始化页面加载的5种状态
public static final int STATE_UNKOWN = 0;
public static final int STATE_LOADING = 1;
public static final int STATE_ERROR = 2;
public static final int STATE_EMPTY = 3;
public static final int STATE_SUCCESS = 4;
public int state = STATE_UNKOWN;
private View loadingView;// 加载中的界面
private View errorView;// 错误界面
private View emptyView;// 空界面
private View successView;// 加载成功的界面
private FrameLayout frameLayout;
//创建一个View对象
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(frameLayout == null){
frameLayout = new FrameLayout(getActivity());
init(); // 在FrameLayout中 添加4种不同的界面:加载中, 加载错误,加载为空 ,加载成功
}else{
ViewUtils.removeParent(frameLayout);
}
//show();// 根据服务器的数据 切换状态
return frameLayout;
}
// 在FrameLayout中 添加4种不同的界面:加载中, 加载错误,加载为空 ,加载成功
private void init() {
// 创建了加载中的界面
loadingView = createLoadingView();
if (loadingView != null) {
frameLayout.addView(loadingView, new FrameLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
}
// 加载错误界面
errorView = createErrorView();
if (errorView != null) {
frameLayout.addView(errorView, new FrameLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
}
// 加载空的界面
emptyView = createEmptyView();
if (emptyView != null) {
frameLayout.addView(emptyView, new FrameLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
}
// 根据不同的状态显示不同的界面
showPage();
}
//根据不同的状态显示不同的界面
private void showPage(){
//利用||,显示加载界面
if (loadingView != null) {
loadingView.setVisibility(state == STATE_UNKOWN
|| state == STATE_LOADING ? View.VISIBLE : View.INVISIBLE);
}
//利用||,显示错误界面
if (errorView != null) {
errorView.setVisibility(state == STATE_ERROR ? View.VISIBLE
: View.INVISIBLE);
}
//利用||,显示空界面
if (emptyView != null) {
emptyView.setVisibility(state == STATE_EMPTY ? View.VISIBLE
: View.INVISIBLE);
}
if (state == STATE_SUCCESS) {
//创建成功的时候加载成功页面
successView = createSuccessView();
if (successView != null) {
frameLayout.addView(successView, new FrameLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
successView.setVisibility(View.VISIBLE);
}
}else{
//不成功的时候让页面隐藏
if(successView != null){
successView.setVisibility(View.INVISIBLE);
}
}
}
//加载成功的界面
public abstract View createSuccessView();
/* 创建加载中的界面 */
private View createErrorView() {
View view = View.inflate(getActivity(), R.layout.loadpage_error, null);
//点击按钮重新请求服务器更新界面
Button page_bt = (Button) view.findViewById(R.id.page_bt);
page_bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
show();
}
});
return view;
}
/* 加载错误界面 */
private View createEmptyView() {
View view = View.inflate(getActivity(), R.layout.loadpage_empty, null);
return view;
}
/* 加载空的界面 */
private View createLoadingView() {
View view = View.inflate(getActivity(), R.layout.loadpage_loading, null);
return view;
}
//更具服务器获取的状态显示界面
public void show() {
//更新状态,当加载错误以后或者加载了空页面时候需要更新一下状态
if (state == STATE_ERROR || state == STATE_EMPTY) {
state = STATE_LOADING;
}
// 请求服务器 获取服务器上数据 进行判断
// 请求服务器 返回一个结果
//子线程中请求服务器,同时休眠一下
new Thread() {
public void run() {
//休眠2s
SystemClock.sleep(2000);
final LoadResult result = load();
if (getActivity() != null) {
//主线程刷新界面
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if(result != null){
//更新状态
state = result.getValue();
//更新界面
showPage();
}
}
});
}
};
}.start();
showPage();
}
//服务器返回的数据
protected abstract LoadResult load();
//服务器返回的枚举结果,来显示界面
public enum LoadResult{
error(2), empty(3), success(4);
int value;
//获取服务器返回的结果
LoadResult(int value) {
this.value = value;
}
//获取到value
public int getValue() {
return value;
}
}
}
HomeFragment.java
package com.ldw.market.fragment;
import com.ldw.market.R;
import com.ldw.market.fragment.BaseFragment.LoadResult;
import com.ldw.market.utils.ViewUtils;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.TextView;
/*
* Home页面,主体的加载的几个页面和服务器请求数据都是在BaseFragment中去实现
*/
public class HomeFragment extends BaseFragment {
// 当Fragment挂载的activity创建的时候调用
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
show();
}
public View createSuccessView() {
TextView tv = new TextView(getActivity());
tv.setText("加载成功了....");
tv.setTextSize(30);
return tv;
}
@Override
public LoadResult load() {
// TODO Auto-generated method stub
return LoadResult.success;
}
}
package com.ldw.market;
import com.ldw.market.fragment.AppFragment;
import com.ldw.market.fragment.BaseFragment;
import com.ldw.market.fragment.FragmentFactory;
import com.ldw.market.fragment.HomeFragment;
import com.ldw.market.utils.UiUtils;
import junit.framework.AssertionFailedError;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.Tab;
import android.support.v7.app.ActionBar.TabListener;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.SearchView.OnQueryTextListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends BaseActivity implements OnQueryTextListener{
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle drawerToggle;
private ViewPager mViewPager;
private PagerTabStrip pager_tab_strip;
private String[] tab_names; // 标签的名字
//加载字符串数组,初始化Tab
@Override
protected void init() {
tab_names = UiUtils.getStringArray(R.array.tab_names);
}
//初始化ActionBar
@Override
protected void initActionBar() {
//添加tab标签名
ActionBar actionBar = getSupportActionBar();
//让拉出显示详情的图片显示,可以拉出详情
actionBar.setDisplayHomeAsUpEnabled(true);
//让按键点击有效
actionBar.setHomeButtonEnabled(true);
//ActionBarDrawerToggle是ActionBar控制抽屉,
//参数1:当前actionBar的Activity,参数2:控制的抽屉,参数3:按钮的图片,参数4和5是描述
drawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout, R.drawable.ic_drawer_am, R.string.open_drawer,
R.string.close_drawer){
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
Toast.makeText(getApplicationContext(), "抽屉关闭了", 0).show();
}
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
Toast.makeText(getApplicationContext(), "抽屉打开了", 0).show();
}
};
//设置监听DrawerListener
mDrawerLayout.setDrawerListener(drawerToggle);
// 让开关和actionbar建立关系
drawerToggle.syncState();
}
//初始化界面
@Override
protected void initView(){
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.dl);
mViewPager=(ViewPager) findViewById(R.id.vp);
pager_tab_strip = (PagerTabStrip) findViewById(R.id.pager_tab_strip);
// 设置标签下划线的颜色
pager_tab_strip.setTabIndicatorColor(getResources().getColor(R.color.indicatorcolor));
mViewPager.setAdapter(new MainAdapter(getSupportFragmentManager()));
//监听ViewPager,tab改变的时候改变界面
mViewPager.setOnPageChangeListener(new OnPageChangeListener(){
@Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
//条目被选中的时候,更新服务器状态,重新显示界面
@Override
public void onPageSelected(int position) {
BaseFragment createFragment = FragmentFactory.createFragment(position);
createFragment.show();
}
});
}
//可以继承PageAapter实现ViePager翻页现在继承FragmentStatePagerAdapter可以实现fragement
private class MainAdapter extends FragmentStatePagerAdapter{
public MainAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
//每一个条目返回的fragment
@Override
public Fragment getItem(int position) {
// 通过Fragment工厂 生产Fragment
return FragmentFactory.createFragment(position);
}
//条目的总数
@Override
public int getCount() {
// TODO Auto-generated method stub
return tab_names.length;
}
// 返回每个条目的标题,设置tab的标签
@Override
public CharSequence getPageTitle(int position) {
return tab_names[position];
}
}
//初始化ActionBar的界面
@SuppressLint("NewApi") @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
// 如果运行的环境 (部署到什么版本的手机 )大于3.0,低版本的不支持
if (android.os.Build.VERSION.SDK_INT > 11) {
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setOnQueryTextListener(this);// 搜索的监听
}
return true;
}
public void click(View v){
Intent intent = new Intent(getApplicationContext(), DetailActivity.class);
startActivity(intent);
}
/** 处理actionBar菜单条目的点击事件 */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
System.out.println("所有");
//当前点击的条目是search
if (item.getItemId() == R.id.action_search) {
Toast.makeText(getApplicationContext(), "搜索", 0).show();
}
//优先处理drawerToggle的点击,drawerToggle出不不了交给父类
return drawerToggle.onOptionsItemSelected(item)|super.onOptionsItemSelected(item);
}
// 当搜索提交的时候
@Override
public boolean onQueryTextChange(String arg0) {
Toast.makeText(getApplicationContext(), arg0, 0).show();
return false;
}
// 当搜索的文本发生变化
@Override
public boolean onQueryTextSubmit(String arg0) {
Toast.makeText(getApplicationContext(), arg0, 0).show();
return false;
}
}
ViewUtils.java防止frameLayout复用ViewPager,重复的添加到ViewPager。做法是先找到以前的parent,再把parent里面的子类移除,之后再在代码中添加frameLayout
package com.ldw.market.utils;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
public class ViewUtils {
public static void removeParent(View v){
// 先找到爹 在通过爹去移除孩子
ViewParent parent = v.getParent();
//所有的控件 都有爹 爹一般情况下 就是ViewGoup
if(parent instanceof ViewGroup){
ViewGroup group=(ViewGroup) parent;
group.removeView(v);
}
}
}