AndroidPro4_006_Fragments

来源:互联网 发布:浪潮软件股票代码 编辑:程序博客网 时间:2024/06/05 18:29
# Ensure that there’s a default constructor for your fragment class.
    When the system restores a fragment, it calls the default constructor (with no arguments) and then restores this bundle of arguments to the newly created     fragment.

# Add a bundle of arguments as soon as you create a new fragment so these subsequent methods can properly set up your fragment, and so the system can restore your fragment properly when necessary.

# A fragment can save state into a bundle object when the fragment is being re-created, and this bundle object gets given back to the fragment’s onCreate() callback. This saved bundle is also passed to onInflate(), onCreateView(), and onActivityCreated(). 
    Note that this is not the same bundle as the one attached as initialization arguments. This bundle is one in which you are likely to store the current state of the fragment, not the values that should be used to initialize it.

# Fragment Lifecycle
newInstance() method,take the appropriate number and type of arguments, and then build the arguments bundle appropriately. 
public static MyFragment newInstance(int index) {
    MyFragment f = new MyFragment();
    Bundle args = new Bundle();
    args.putInt(“index”, index);
    f.setArguments(args);
    return f;
}
    \ onInflate()
    如果 fragment 定义在layout的XML里有<fragment> tag, onInflate()会被调用(就像有layout时activity的setContentView()一样).
    
    \ onAttach()
    This callback invoked after fragment is associated with its activity. getActivity()可以获得associted activity.
    在整个lifecycle中,getArguments()都可获得初始化fragment时的args,但是当fragment is attached to its activity,就不能再调用setArguments() method了.

    \ onCreated()
    Activity的onCreate()结束后调用. This callback gets the saved state bundle passed in.
    This callback is about as early as possible to create a background thread to get data that this fragment will need. Your fragment code is running on the UI thread, and you don’t want to do disk I/O or network accesses on the UI thread.

    \ onCreateView()
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if(container == null)
        return null;
    View v = inflater.inflate(R.layout.details, container, false);
    TextView text1 = (TextView) v.findViewById(R.id.text1);
    text1.setText(myDataSet[ getPosition() ] );
    return v;
}
    important: do not attach the fragment’s view to the container parent in this callback
    \ onActivityCreated()
    This is called after the activity has completed its onCreate() callback.
    This is where you can do final tweaks to the user interface before the user sees it, be sure that any other fragment for this activity has been attached to your activity.
    \ onStart()
    This callback is tied to the activity’s onStart(). put your logic into the fragment’s onStart()

    \ onResume()
    This callback is tied to the activity’s onResume(). 
    \ onPause()
    Tied to the activity’s onPause()

    \ onSaveInstanceState()
     Usually called right after onPause(), can occur any time before onDestroy().

    \ onStop()
    This one is tied to the activity’s onStop(), A fragment that has been stopped could go straight back to the onStart() callback, which then leads to onResume().

    \ onDestroyView()
    \ onDestroy()
    Note that it is still attached to the activity and is still findable, but it can’t do much.

    \ onDetach() 
    The final callback in a fragment’s lifecycle.Once this is invoked, the fragment is not tied to its activity, release all its resources.

# Your Activity’s Layout XML for Landscape Mode
<?xml version="1.0" encoding="utf-8"?>
<!-- This file is res/layout-land/main.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    <fragment class="com.androidbook.fragments.bard.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="2"
        android:layout_width="0px"
        android:layout_height="match_parent" />
</LinearLayout>
    Note: <fragment> tag 不接受任何子tag. 
            这只是activity的layout, 设置了fragment的位置,但是并没有定义他,所以必须再后面定义 in code. 

# Main Activity Code:
public boolean isMultiPane() {
    return getResources().getConfiguration().orientation
     == Configuration.ORIENTATION_LANDSCAPE;
}
/**
* 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.
*/
public void showDetails(int index) {
    Log.v(TAG, "in MainActivity showDetails(" + index + ")");
    if (isMultiPane()) {
        // Check what fragment is 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.
            Log.v(TAG, "about to run FragmentTransaction");
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); // 必须在 replace()之前调用,否则无效果.
            //ft.addToBackStack("details");
            ft.replace(R.id.details, details); // 可以用remove()和add()来代替replace().
            ft.commit();    // 让UI thread 准备更新.
        }
    } else {
    // Otherwise you need to launch a new activity to display
    // the dialog fragment with selected text.
    Intent intent = new Intent();
    intent.setClass(this, DetailsActivity.class);
    intent.putExtra("index", index);
    startActivity(intent);
    }
}

    \ Source Code for DetailsFragment
public class DetailsFragment extends Fragment {
    private int mIndex = 0;
    public static DetailsFragment newInstance(int index) {
        Log.v(MainActivity.TAG, "in DetailsFragment newInstance(" + index + ")");
        DetailsFragment df = new DetailsFragment();
        // Supply index input as an argument.
        Bundle args = new Bundle();
        args.putInt("index", index);
        df.setArguments(args);
        return df;
    }
    public static DetailsFragment newInstance(Bundle bundle) {
        int index = bundle.getInt("index", 0);
        return newInstance(index);
    }
    @Override
    public void onCreate(Bundle myBundle) {
        Log.v(MainActivity.TAG, "in DetailsFragment onCreate. Bundle contains:");
        if(myBundle != null) {
            for(String key : myBundle.keySet()) {
                Log.v(MainActivity.TAG, " " + key);
            }
        }
        else {
            Log.v(MainActivity.TAG, "myBundle is null");
        }
        super.onCreate(myBundle);
        mIndex = getArguments().getInt("index", 0); // 为什么不简单的在newInstance()中getArguments呢?因为android会用默认构造函数 re-create fragment,而默认构造函                                                                       // 数不会调用你的newInstance(). (那newInstance()有什么价值?)
    }
    public int getShownIndex() {
    return mIndex;
    }
    @Override
    public View onCreateView(LayoutInflater inflater,
    ViewGroup container, Bundle savedInstanceState) {
        Log.v(MainActivity.TAG, "in DetailsFragment onCreateView. container = " + container);
        // Don't tie this fragment to anything through the inflater.
        // Android takes care of attaching fragments for us. The
        // container is only passed in so you can know about the
        // container where this View hierarchy is going to go.
        View v = inflater.inflate(R.layout.details, container, false);    // R.layout.details 对应下面的details.XML
        TextView text1 = (TextView) v.findViewById(R.id.text1);
         text1.setText(Shakespeare.DIALOGUE[ mIndex ] );
        return v;
     }
}
    The details.xml Layout File for the Details Fragment
<?xml version="1.0" encoding="utf-8"?>
<!-- This file is res/layout/details.xml -->
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ScrollView android:id="@+id/scroller"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    <TextView android:id="@+id/text1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    </ScrollView>
</LinearLayout>
    可以把这个layout放在/res/layout 下,这样他就是一个default layout(不同于/res/layout-land),

# FragmentTransactions
    \ A fragment must live inside a view container, also known as a view group.
    \ FrameLayout is a good choice as the container for the details fragment in the main.xml layout file of your activity. 
    \ 如果不用FrameLayout ,就不能swap.
    \ FrameLayout swap via FragmentTransactions 
# FragmentManager
    Fragmentmanager 属于 activity. 用于管理fragment.