天天看点

190.m1-Fragment显示界面

利用Fragment显示界面

1.首先初始化几种界面,添加到Fragment中

2.然后根据不同的状态显示不同的界面,显示的过程中需要向服务器请求数据,服务器请求数据需要在子线程中请求,同时利用runOnUiThread在主线程中刷新UI

MainActivity.java初始化显示的Fragment

package com.ldw.market;

import com.ldw.market.fragment.AppFragment;
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()));
    }
    
    //可以继承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;
	}
	
    
}
           

FragmentFactory.java来加工初始化显示哪一个Fragment

package com.ldw.market.fragment;

import java.util.HashMap;
import java.util.Map;

import android.support.v4.app.Fragment;

/*
 * 通过Fragment工厂  生产Fragment  
 */
public class FragmentFactory {
	//创建一个Map,fragment中放在集合中,第一个参数是脚标,第二个是fRAGMENT
	private static Map<Integer, BaseFragment1> mFragments = new HashMap<Integer, BaseFragment1>();
	
	public static BaseFragment1 createFragment(int position) {
		BaseFragment1 fragment = null;
		//在集合中取出来Fragment
		fragment = mFragments.get(position); 
		//如果再集合中没有取出来 需要重新创建
		if (fragment == null) {  
			if (position == 0) {
				fragment = new HomeFragment();
			} else if (position == 1) {
				fragment = new AppFragment();
			} else if (position == 2) {
				fragment = new GameFragment();
			} else if (position == 3) {
				fragment = new SubjectFragment();
			} else if (position == 4) {
				fragment = new CategoryFragment();
			} else if (position == 5) {
				fragment = new TopFragment();
			}
			//保存fragment
			if (fragment != null) {
				mFragments.put(position, fragment);// 把创建好的Fragment存放到集合中缓存起来
			}
		}
		return fragment;
	}
}
           

HomeFragment.java显示Home的Fragment的逻辑代码,里面有初始化需要加载的页面以及一些逻辑的判断

package com.ldw.market.fragment;

import com.ldw.market.R;

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;

public class HomeFragment 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 static int state = STATE_UNKOWN;
	
	//创建一个View对象
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		frameLayout = new FrameLayout(getActivity());
		init(); // 在FrameLayout中 添加4种不同的界面:加载中, 加载错误,加载为空 ,加载成功
		show();// 根据服务器的数据 切换状态
		
		return frameLayout;
		
	}
	
	private View loadingView;// 加载中的界面
	private View errorView;// 错误界面
	private View emptyView;// 空界面
	private View successView;// 加载成功的界面
	private FrameLayout 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);
		}
	}
	
	//服务器返回的枚举结果,来显示界面
	public enum LoadResult{
		error(2), empty(3), success(4);

		int value;
		//获取服务器返回的结果
		LoadResult(int value) {
			this.value = value;
		}

		//获取到value
		public int getValue() {
			return value;
		}

	}
	
	//更具服务器获取的状态显示界面
	private 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();
	}
	
	private LoadResult load() {

		return LoadResult.error;
	}
	
	/* 创建加载中的界面 */
	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;
	}
}