動態添加fragment與手勢切換(三)(android)

繼續,現在開始寫最重要的,實現代碼了,我們需要建立一個activity ,注意我的例子中的activity 不是主頁,這裏直接上代碼,看注析吧。

1、activity 的佈局如下:

<LinearLayout 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="#ffffff"
    xmlns:android="http://schemas.android.com/apk/res/android">

   <RelativeLayout
         android:id="@+id/relativeLayout1"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:background="@drawable/wbg" >

      <!-- 此layout 可以顯示主要的信息內容 -->
      <FrameLayout
           android:id="@+id/frameLayout1"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"  >
      </FrameLayout>
       
       <!-- 此layout 可以顯示的fragment數量與當前fragment位置-->
      <FrameLayout
           android:id="@+id/frameLayout2"
           android:layout_width="match_parent"
           android:layout_height="match_parent" 
           android:layout_marginBottom="100dp">
           
              <LinearLayout
		        android:id="@+id/layout_fragment_num"
		        android:layout_width="match_parent"
		        android:layout_height="44dp"
		        android:orientation="horizontal"
		        android:layout_gravity="bottom"
		        android:background="@color/gray"
		        android:gravity="center_vertical|center_horizontal" > 
              </LinearLayout>

           
       </FrameLayout>
       
      <!-- 此layout 可以顯示當前內容的附屬信息-->
      <FrameLayout
          android:id="@+id/frameLayout3"
           android:layout_width="match_parent"
           android:layout_height="match_parent" 
           android:layout_marginBottom="0dp"
           >
           
              <LinearLayout
		        android:id="@+id/layout_fragment_bottom" 
		        android:layout_width="match_parent"
		        android:layout_height="100dp"
		        android:orientation="horizontal"
		        android:layout_gravity="bottom"
		        android:background="#cccccc"
		        >
		        
              </LinearLayout>
       </FrameLayout>
      
         
     </RelativeLayout>
    
     
</LinearLayout>

2、Java代碼

package com.example.testandroid;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

public class FragmentChangeActivity extends    FragmentActivity implements OnGestureListener {

	private static TextView[] numTexts;
    public static Fragment[] fragments1;
    public static Fragment[] fragments2;

    /**定義手勢檢測實例*/
    public static GestureDetector detector;
    /**做標籤,記錄當前是哪個fragment*/
    public int MARK=0;
    /**定義手勢兩點之間的最小距離*/
    final int DISTANT=50; 
	
	private LinearLayout layout_fragment_num;
	private LinearLayout layout_fragment_bottom;
	private FrameLayout frameLayout1;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);//隱藏標題    
		setContentView(R.layout.activity_fragment_change);
		
		frameLayout1=(FrameLayout) this.findViewById(R.id.frameLayout1);
		
		//改變layout的透明度
		layout_fragment_num=(LinearLayout) this.findViewById(R.id.layout_fragment_num);
		layout_fragment_num.getBackground().setAlpha(100);//0-255,透明-不透明
		
		//改變layout的透明度
		layout_fragment_bottom=(LinearLayout) this.findViewById(R.id.layout_fragment_bottom);
		layout_fragment_bottom.getBackground().setAlpha(0);
		
		//假設當前需要動態添加3個
		initTextViewToLayout(3,this);
		changeTextViewColor(0);
		
		setfragment();
		
        //創建手勢檢測器
     // 注意前一個this代表的是一個Context,後一個this代表的是一個OnGestureListener。
        detector=new GestureDetector(this,this);
	}

	/**
	 * 動態添加TEXTVIEW
	 */
	private void initTextViewToLayout(int num,Context context){
		numTexts=new TextView[num];
		for(int i=0;i<num;i++){
			TextView tv=new TextView(context);
			tv.setText("●");
			tv.setTextColor(getResources().getColor(R.color.gray1));
			numTexts[i]=tv;
			layout_fragment_num.addView(tv);
		}
		
	}
	/**
	 * 改變TEXTVIEW的顏色
	 * @param mark
	 */
	private void changeTextViewColor(int mark){
		
		for(int i=0;i<numTexts.length;i++){
			numTexts[i].setTextColor(getResources().getColor(R.color.gray1));
		}
		numTexts[mark].setTextColor(getResources().getColor(R.color.white));
	}
	
	
	
	
    /**初始化fragment*/
    public void setfragment()
    {
        fragments1=new Fragment[3];
        fragments2=new Fragment[3];

        fragments1[0]=new TabOfFragment01();
        fragments1[1]=new TabOfFragment01();
        fragments1[2]=new TabOfFragment01();
        fragments2[0]=new TabOfFragment02();
        fragments2[1]=new TabOfFragment02();
        fragments2[2]=new TabOfFragment02();
        
        getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout1, fragments1[0]).commit();
        getSupportFragmentManager().beginTransaction().replace(R.id.layout_fragment_bottom, fragments2[0]).commit();
        
    }


	
    /**
     * 設置動畫
     * @param ft
     * @param slefId
     */
    private void setAnim(FragmentTransaction ft,int slefId){
        if(MARK>slefId)
        	ft.setCustomAnimations(R.anim.in_to_left, R.anim.out_to_right);
        
        if(MARK<slefId)
        	 ft.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left);
          	
    	
    }
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.fragment_change, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        //將該Activity上觸碰事件交給GestureDetector處理
        return detector.onTouchEvent(event);
    }
	
	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onFling(MotionEvent arg0, MotionEvent arg1, float velocityX,
			float velocityY) {
		// TODO Auto-generated method stub
        
        
        FragmentTransaction ft=getSupportFragmentManager().beginTransaction();
        FragmentTransaction ft1=getSupportFragmentManager().beginTransaction();
        Bundle bundle = new Bundle();  
        int tmpMark=1;
        
        System.out.println(arg0.getX()+"---"+arg1.getX());
        //當是Fragment0的時候
        if(MARK==0)
        {
            if(arg0.getX()>arg1.getX()+DISTANT)
            {
            	tmpMark=1;
      	        bundle.putString("pageNo", "1");  
                fragments1[tmpMark].setArguments(bundle);
                setAnim(ft,tmpMark);
                setAnim(ft1,tmpMark);
               
                ft.replace(R.id.frameLayout1, fragments1[tmpMark]).commit();
                ft1.replace(R.id.layout_fragment_bottom, fragments2[tmpMark]).commit();
            	
                this.changeTextViewColor(tmpMark);
                MARK=tmpMark;
            }
            else
            {

            }
            
        }
        //當是Fragment1的時候
        else if (MARK>=1 && MARK<numTexts.length-1)
        {
            if(arg0.getX()>arg1.getX()+DISTANT)
            {
            	tmpMark=MARK+1;
      	        bundle.putString("pageNo", ""+(tmpMark+1));  
                fragments1[tmpMark].setArguments(bundle);
                fragments2[tmpMark].setArguments(bundle);
                setAnim(ft,tmpMark);
                setAnim(ft1,tmpMark);
               
                ft.replace(R.id.frameLayout1, fragments1[tmpMark]).commit();
                ft1.replace(R.id.layout_fragment_bottom, fragments2[tmpMark]).commit();
            	
                this.changeTextViewColor(tmpMark);
                MARK=tmpMark;
            }
            else if(arg1.getX()>arg0.getX()+DISTANT)
            {
            	tmpMark=MARK-1;
      	        bundle.putString("pageNo", ""+(tmpMark+1));  
                fragments1[tmpMark].setArguments(bundle);
                fragments2[tmpMark].setArguments(bundle);
                setAnim(ft,tmpMark);
                setAnim(ft1,tmpMark);
               
                ft.replace(R.id.frameLayout1, fragments1[tmpMark]).commit();
                ft1.replace(R.id.layout_fragment_bottom, fragments2[tmpMark]).commit();
                
                this.changeTextViewColor(tmpMark);
                MARK=tmpMark;
            }
            else
            {

            }
        }
        //當是Fragment5的時候
        else if(MARK==numTexts.length-1)
        {
            if(arg1.getX()>arg0.getX()+DISTANT)
            {
            	tmpMark=(numTexts.length-1)-1;
     	        bundle.putString("pageNo", ""+(tmpMark+1));  
                fragments1[tmpMark].setArguments(bundle);
                fragments2[tmpMark].setArguments(bundle);
                setAnim(ft,tmpMark);
                setAnim(ft1,tmpMark);
               
                ft.replace(R.id.frameLayout1, fragments1[tmpMark]).commit();
                ft1.replace(R.id.layout_fragment_bottom, fragments2[tmpMark]).commit();
                
                this.changeTextViewColor(tmpMark);
                MARK=tmpMark;
            }
            else
            {

            }
        }
        return false;
	}
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章