Fragment的简单demo

package com.example.googleandroiddemo;
//
//import android.app.Activity;
//import android.os.Bundle;
//import android.support.v4.app.FragmentTransaction;
//import android.support.v4.app.ListFragment;
//import android.view.View;
//import android.widget.ArrayAdapter;
//import android.widget.ListView;
//
//public class MainActivity extends Activity {
//	@Override
//	protected void onCreate(Bundle savedInstanceState) {
//		super.onCreate(savedInstanceState);
//
//		setContentView(R.layout.fragment_layout);
//	}
//	
//	
//	public static class TitlesFragment extends ListFragment {
//		public TitlesFragment() {
//			super();
//			// TODO Auto-generated constructor stub
//		}
//		
//	    public static TitlesFragment newInstance(int index) {
//	    	TitlesFragment f = new TitlesFragment();
//
//	        // Supply index input as an argument.
////	        Bundle args = new Bundle();
////	        args.putInt("index", index);
////	        f.setArguments(args);
//
//	        return f;
//	    }
//
//		boolean mDualPane;
//		int mCurCheckPosition = 0;
//		String str[] = { "321321", "312312", "312312", "321321312","eqweqwewqeqw","eqwewqeqwwe","eqweqweqwerewre","r4r4r4t","eqwewqe" };
//		@Override
//		public void onActivityCreated(Bundle savedInstanceState) {
//			super.onActivityCreated(savedInstanceState);
//
//			// Populate list with our static array of titles.
//			setListAdapter(new ArrayAdapter<String>(getActivity(),
//					android.R.layout.simple_list_item_activated_1,
//					str));
//
//			// Check to see if we have a frame in which to embed the details
//			// fragment directly in the containing UI.
//			View detailsFrame = getActivity().findViewById(R.id.details);
//			mDualPane = detailsFrame != null
//					&& detailsFrame.getVisibility() == View.VISIBLE;
//
//			if (savedInstanceState != null) {
//				// Restore last state for checked position.
//				mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
//			}
//
//			if (mDualPane) {
//				// In dual-pane mode, the list view highlights the selected item.
//				getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
//				// Make sure our UI is in the correct state.
//				showDetails(mCurCheckPosition);
//			}
//		}
//
//		@Override
//		public void onSaveInstanceState(Bundle outState) {
//			super.onSaveInstanceState(outState);
//			outState.putInt("curChoice", mCurCheckPosition);
//		}
//
//		@Override
//		public void onListItemClick(ListView l, View v, int position, long id) {
//			showDetails(position);
//		}
//
//		/**
//		 * Helper function to show the details of a selected item, either by
//		 * displaying a fragment in-place in the current UI, or starting a whole new
//		 * activity in which it is displayed.
//		 */
//		void showDetails(int index) {
//			mCurCheckPosition = index;
//
//			if (mDualPane) {
//				// We can display everything in-place with fragments, so update
//				// the list to highlight the selected item and show the data.
//				getListView().setItemChecked(index, true);
//
//				// Check what fragment is currently shown, replace if needed.
//				DetailsFragment details = (DetailsFragment) getFragmentManager()
//						.findFragmentById(R.id.details);
//				if (details == null || details.getShownIndex() != index) {
//					// Make new fragment to show this selection.
//					details = DetailsFragment.newInstance(index);
//
//					// Execute a transaction, replacing any existing fragment
//					// with this one inside the frame.
//					FragmentTransaction ft = getFragmentManager()
//							.beginTransaction();
//					ft.replace(R.id.details, details);
//					ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
//					ft.commit();
//				}
//
//			} else {
//				// Otherwise we need to launch a new activity to display
//				// the dialog fragment with selected text.
//				// Intent intent = new Intent();
//				// intent.setClass(getActivity(), DetailsActivity.class);
//				// intent.putExtra("index", index);
//				// startActivity(intent);
//			}
//		}
//	}
//}


import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.ListFragment;
import android.os.Bundle;
//import android.support.v4.app.Fragment;
//import android.support.v4.app.FragmentTransaction;
//import android.support.v4.app.ListFragment;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;


public class MainActivity extends Activity {

    public static String[] array = { "text1,", "text2", "text3", "text4",
            "text5,", "text6", "text7", "text8" };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.fragment_layout);
    }

        
    public static class TitlesFragment extends ListFragment {

        boolean mDualPane;
        int mCurCheckPosition = 0;
        
        @Override
        public void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            System.out.println("Fragment-->onCreate");
        }
        
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            System.out.println("Fragment-->onCreateView");
            return super.onCreateView(inflater, container, savedInstanceState);
        }
        
        @Override
        public void onPause() {
            // TODO Auto-generated method stub
            super.onPause();
            System.out.println("Fragment-->onPause");
        }
        
        
        @Override
        public void onStop() {
            // TODO Auto-generated method stub
            super.onStop();
            
            System.out.println("Fragment-->onStop");
        }
        
        @Override
        public void onAttach(Activity activity) {
            // TODO Auto-generated method stub
            super.onAttach(activity);
            System.out.println("Fragment-->onAttach");
        }
        
        @Override
        public void onStart() {
            // TODO Auto-generated method stub
            super.onStart();
            System.out.println("Fragment-->onStart");
        }
        
        @Override
        public void onResume() {
            // TODO Auto-generated method stub
            super.onResume();
            System.out.println("Fragment-->onResume");
        }
        
        @Override
        public void onDestroy() {
            // TODO Auto-generated method stub
            super.onDestroy();
            System.out.println("Fragment-->onDestroy");
        }
        
        

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onActivityCreated(savedInstanceState);
            System.out.println("Fragment-->onActivityCreted");
            setListAdapter(new ArrayAdapter<String>(getActivity(),
                    android.R.layout.simple_list_item_1, array));

            View detailsFrame = getActivity().findViewById(R.id.details);

            mDualPane = detailsFrame != null
                    && detailsFrame.getVisibility() == View.VISIBLE;

            if (savedInstanceState != null) {
                mCurCheckPosition = savedInstanceState.getInt("curChoice", 0); //从保存的状态中取出数据
            }

            if (mDualPane) {
                getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);

                showDetails(mCurCheckPosition);
            }
        }

        @Override
        public void onSaveInstanceState(Bundle outState) {
            // TODO Auto-generated method stub
            super.onSaveInstanceState(outState);

            outState.putInt("curChoice", mCurCheckPosition);//保存当前的下标
        }

        @Override
        public void onListItemClick(ListView l, View v, int position, long id) {
            // TODO Auto-generated method stub
            super.onListItemClick(l, v, position, id);
            showDetails(position);
        }

        void showDetails(int index) {
            mCurCheckPosition = index; 
            if (mDualPane) {
                getListView().setItemChecked(index, true);
                DetailsFragment details = (DetailsFragment) getFragmentManager()
                        .findFragmentById(R.id.details); 
                if (details == null || details.getShownIndex() != index) {
                    details = DetailsFragment.newInstance(mCurCheckPosition); 

                    //得到一个fragment 事务(类似sqlite的操作)
                    FragmentTransaction ft = getFragmentManager()
                            .beginTransaction();
                    ft.replace(R.id.details, details);//将得到的fragment 替换当前的viewGroup内容,add则不替换会依次累加
                    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);//设置动画效果
                    ft.commit();//提交
                }
            } else {
                new AlertDialog.Builder(getActivity()).setTitle(
                        android.R.string.dialog_alert_title).setMessage(
                        array[index]).setPositiveButton(android.R.string.ok,
                        null).show();
            }
        }
    }

    /**
     * 作为界面的一部分,为fragment 提供一个layout
     * @author terry
     *
     */
    public static class DetailsFragment extends Fragment {

        public static DetailsFragment newInstance(int index) { 
            DetailsFragment details = new DetailsFragment();
            Bundle args = new Bundle();
            args.putInt("index", index);
            details.setArguments(args);
            return details;
        }

        public int getShownIndex() {
            return getArguments().getInt("index", 0);
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            if (container == null)
                return null;

            ScrollView scroller = new ScrollView(getActivity());
            TextView text = new TextView(getActivity());

            int padding = (int) TypedValue.applyDimension(
                    TypedValue.COMPLEX_UNIT_DIP, 4, getActivity()
                            .getResources().getDisplayMetrics());
            text.setPadding(padding, padding, padding, padding);
            scroller.addView(text);

            text.setText(array[getShownIndex()]);
            return scroller;
        }
    }
}


xml


<?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"
    android:orientation="horizontal" >

   <fragment class="com.example.googleandroiddemo.MainActivity$TitlesFragment" android:id="@+id/titles" android:layout_weight="1"
       android:layout_width="0px" android:layout_height="match_parent"
       />
   
   <FrameLayout android:id="@+id/details" android:layout_weight="1" android:layout_width="0px" android:layout_height="match_parent"
       android:background="?android:attr/detailsElementBackground"
       ></FrameLayout>
</LinearLayout>

猜你喜欢

转载自hellorheaven.iteye.com/blog/1836728