关于在android项目中使用fragment的个人心得

在android应用的开发过程中,我使用过fragment来进行快速开发,我们知道java web中的iframe。这个时候,fragment就有这个用途了。

这个fragment是android.support.v4.app.Fragmet

一、定义基础的BaseFragmentActivity

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Toast;

public abstract class BaseFragmentActivity extends FragmentActivity implements OnClickListener{

	protected boolean savedState = false;

	protected CommandListener commandlistener;         //很重要,把activity中的命令,传递给fragment
	
	/********************************************/

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
	}

        /***********************************************/
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
		if(commandlistener!=null){
			commandlistener.execute(v);
		}
		
	}

	public void setCommandlistener(CommandListener commandlistener) {
		this.commandlistener = commandlistener;
	}
	
	public interface CommandListener
	{
		public void execute(View v);
	}
	
}

二、定义你baselayout布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent">


</LinearLayout>

三、定义BaseFragment

import android.os.Bundle;

import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class BaseFragment extends Fragment{

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.baselayout, container, false);  
	}
	
	
}

四、定义应用的主界面fragment_main

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/control_popuplay"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#eee"
    android:orientation="vertical" >

    <include
        android:id="@+id/fragment_main_top"
        android:layout_width="match_parent"
        android:layout_height="@dimen/title_height"
        android:layout_alignParentTop="true"
        layout="@layout/title_view" />

    <include
        android:id="@+id/bottom"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:layout_alignParentBottom="true"
        layout="@layout/bottom_view" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/bottom"
        android:layout_below="@+id/fragment_main_top"
        android:orientation="vertical" >

        <fragment
            android:id="@+id/mainfragment"
            android:name="com.company.waiqing.activity.fragments.BaseFragment"
            android:layout_width="fill_parent"
            android:layout_height="match_parent" />
    </LinearLayout>
</RelativeLayout>

 从上面的代码可以看出,这个时候的主界面

效果图如下:
关于在android项目中使用fragment的个人心得
 

五、定义自己的BaseMainActivity

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;

import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public abstract class BaseMainActivity extends BaseFragmentActivity		{

	protected ImageView left_button;             //头部栏的左边的按钮
	protected TextView title;                          //头部栏的标题
	protected ImageView rightbutton;             //头部栏的右边按钮
	protected RelativeLayout bottom;             //底部栏的布局

	
	private Popup_holder holder;                   //弹出框
	protected PopupWindow window;
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_UP
				&& event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			BaseMainActivity.this.finish();
			return true;
		}
		if (event.getAction() == KeyEvent.ACTION_DOWN
				&& event.getKeyCode() == KeyEvent.KEYCODE_MENU) {
			return true;
		}
		return super.dispatchKeyEvent(event); // 按下其他按钮,调用父类进行默认处理
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		//打开Activity隐藏软键盘;
		getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		
		setContentView(R.layout.fragment_main);
		Logger.i("test", "initUI");
		initUI();
		initTitle();
		run();
		initFragment(); // 初始化fragment
	}

	private void initUI() {
		bottom=(RelativeLayout) findViewById(R.id.bottom);
	}

	public abstract void run();

	protected void initTitle() {
		left_button = (ImageView) findViewById(R.id.iv_left_button);
		title = (TextView) findViewById(R.id.title_text);
		rightbutton = (ImageView) findViewById(R.id.iv_right_button);
		left_button.setOnClickListener(topviewlisterner);
		rightbutton.setOnClickListener(topviewlisterner);
		// back.setImageResource(R.drawable.back_icon);
		// back.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		// finish();
		// }
		// });
	}
	
	

	
	private void initFragment() {
		Logger.i("test", "initFragment");
		CommonFragment f = (CommonFragment) setFragment();
		Logger.i("test", "status:" + savedState);

		if (f != null) {
			f.setRefreshListener(this);
			fragmentchage(f);
		}
	}

	// 设置中间的fragment
	protected Fragment setFragment() {
		return null;
	}

	// 设置当前的fragment界面
	private void fragmentchage(Fragment newFragment) {
		FragmentManager fragmentManager = getSupportFragmentManager();
		FragmentTransaction fragmentTransaction = fragmentManager
				.beginTransaction();
		fragmentTransaction.replace(R.id.mainfragment, newFragment);
		fragmentTransaction.commit();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
//		FragmentManager fragmentManager = getSupportFragmentManager();
//		Logger.i("test", fragmentManager.getBackStackEntryCount() + "");
//		fragmentManager.popBackStack();
		super.onPause();
	}

	//顶部按钮监听器,在这里就可以对顶部按钮进行处理
	OnClickListener topviewlisterner=new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			// 进行弹出窗口
			case R.id.iv_left_button:
				initControlPopupView(v);
				break;
			case R.id.iv_right_button:
				BaseMainActivity.this.finish();
				break;
				}
		}
	};
}

六、定义基本的CommonFragment

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * 
 * @author arrau
 *  必须实现commandlistener,这个是用来接收主界面传过来的命令
 */

public abstract class CommonFragment extends Fragment implements CommandListener{

	protected BaseFragmentActivity context;
	protected DestoryListener   destorylistener;
	protected View view;

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		Logger.i(log, "onAttach");
		context = (BaseFragmentActivity) activity;
	}

	public void setFragmentContentView(int layout) {
		view = LayoutInflater.from(context).inflate(layout, null);
		context.setCommandlistener(this);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		Logger.i(log, "onCreateView");
		return view;
	}

	public FragmentManager getSupportFragmentManager() {
		return context.getSupportFragmentManager();
	}

	public View findViewById(int id) {
		return view.findViewById(id);
	}

	public FragmentActivity getContext() {

		return context;
	}

	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		if(destorylistener!=null)
		{
			destorylistener.FragmentDestory(); //当fragment退出时,就让activity退出
		}

		super.onDestroy();
	}
	
	

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		Logger.i(log, "onPause");
		super.onPause();
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		Logger.i(log, "onResume");
		super.onResume();
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		Logger.i(log, "onStart");
		super.onStart();
	}

	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		Logger.i(log, "onStop");
		super.onStop();
	}

	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		Logger.i(log, "move to other view");
		super.onDestroyView();
	}

	
		@Override
	public void execute(View v) {
		// TODO Auto-generated method stub
		
	}
	
	//fragment销毁通知
	public interface DestoryListener
	{
		public void FragmentDestory();
	}

	public DestoryListener getDestorylistener() {
		return destorylistener;
	}

	public void setDestorylistener(DestoryListener destorylistener) {
		this.destorylistener = destorylistener;
	}
}

七、怎么利用

        有的人可能会问,上面这么多代码,我还不如直接一个一个activity写。我的观点是,虽然上面的代码多,但是如果有很多的界面的话,那么就能节约大量的时间,以便以后开发的便利。

       

        以后每个activity都要继承BaseMainActivity

ClientPoolActivity extends BaseMainActivity{

	@Override
	public void run() {
		// TODO Auto-generated method stub
		title.setText("客户池");
	}

	@Override
	protected Fragment setFragment() {
		// TODO Auto-generated method stub
		ClientPoolFragment cf=new ClientPoolFragment();
		return cf;
	}
	
}

每个fragment都要继承ClientNewCreateFragment

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.company.core.utils.IntentUtil;

public class ClientNewCreateFragment extends CommonFragment{
	private Client_Holder holder;
	private ClickListener clistener;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		holder=new Client_Holder();
		clistener=new ClickListener();		
		setFragmentContentView(R.layout.fragment_client_newcreate);//中间部分的layout布局
		holder.t_company=(LinearLayout)findViewById(R.id.fragment_client_newcreate_companylin);
		holder.t_person=(LinearLayout)findViewById(R.id.fragment_client_newcreate_personlin);
		holder.t_company.setOnClickListener(clistener);
		holder.t_person.setOnClickListener(clistener);
		
	}
	
	private class Client_Holder{
		LinearLayout t_company,t_person;
	}


	private class ClickListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
		}
		
	}

                  //这个是得到主界面已经监听过后的view,是BaseMainActivity把按钮事件传过来
                 	@Override
	public void execute(View v) {
		// TODO Auto-generated method stub
                      
		}

}

 这个时候,头部栏都不用以后开发者的配置了,如果有返回,那么当继承这个后就已经配置好了。

相关推荐