Fragment在Activity中的应用 (转载)

原文链接 http://www.cnblogs.com/nanxin/archive/2013/01/24/2875341.html

在本小节中介绍在Activity中创建Fragment。

官网有很详细的介绍http://developer.android.com/guide/components/fragments.html。介绍了Fragment的生命周期,Android3.0引入了Fragmen的概念,使UI灵活地适用于各种设备。具体原理就不多赘述了,请参考官网。

Fragment可以包含于多个Activity,可以使应用适配到不同的屏幕尺寸。当屏幕尺寸足够大时,一个Activity可以包含多个Fragment,不属于这种情况时,会启动另一个Activity包含不同的Fragment。

1 创建一个空的Activity

我们首先创建一个空的Activity,水平排列。如下所示

res/layour/main.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" >
</LinearLayout>

com/fragment/FragmentDemoActivity.java:

复制代码
package com.fragment;

import android.app.Activity;
import android.os.Bundle;

public class FragmentDemoActivity extends Activity {
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main);
    }
}
复制代码

 

2 创建Fragment

我们创建两个Fragment,一个是目录TitlesFragment,一个是详情DetailsFragment。

TitlesFragment集成ListFragment,实现目录列表。

com/fragment/TitlesFragment.java:

复制代码
package com.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class TitlesFragment extends ListFragment {
    static String[] array;

    boolean mDualPane;
    int mCurCheckPosition = 0;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }
    
    @Override
    public void onPause() {
        super.onPause();
    }
    
    
    @Override
    public void onStop() {
        super.onStop();
    }
    
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }
    
    @Override
    public void onStart() {
        super.onStart();
    }
    
    @Override
    public void onResume() {
        super.onResume();
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        array = getResources().getStringArray(R.array.countries_array);
        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) {
        super.onSaveInstanceState(outState);
        outState.putInt("curChoice", mCurCheckPosition);
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        showDetails(mCurCheckPosition);
    }

    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);
                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();
        }
    }

}
复制代码

DetailsFragment显示点击某个目录的详情,com/fragment/DetailsFragment.java:

复制代码
package com.fragment;

import android.app.Fragment;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;
import android.widget.TextView;

public class DetailsFragment extends Fragment {
    static String[] array;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }
    
    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;

        array = getResources().getStringArray(R.array.countries_array);
        
        ScrollView scroller = new ScrollView(getActivity());
        
        /*GridView gridview = (GridView) getActivity().findViewById(R.id.gridview);
        gridview.setAdapter(new ImageAdapter(getActivity()));

        gridview.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                Toast.makeText(DetailsFragment.this.getActivity(), " " + position, Toast.LENGTH_SHORT).show();
            }
        });*/
        
        /*//定义UI组件
        final ImageView iv= (ImageView)getActivity().findViewById(R.id.ImageView01);
        Gallery g = (Gallery) getActivity().findViewById(R.id.Gallery01);

        //设置图片匹配器
        g.setAdapter(new ImageAdapter(getActivity()));

        //设置AdapterView点击监听器,Gallery是AdapterView的子类
        g.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                //显示点击的是第几张图片
                Toast.makeText(DetailsFragment.this.getActivity(), "" + position,
                        Toast.LENGTH_LONG).show();
                //设置背景部分的ImageView显示当前Item的图片
                iv.setImageResource(((ImageView)view).getId());
            }
        });*/
        
        
        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()]);
        
        /*Button btnContact = (Button) getActivity().findViewById(R.id.bt1);
        btnContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(getActivity(), MainHelloGallery.class);
                startActivity(intent);
            }
        });*/
        
        return scroller;
    }
    
    /*@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // TODO Auto-generated method stub
        super.onCreateOptionsMenu(menu, inflater);
         menu.add("Menu 1a").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
            menu.add("Menu 1b").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        Toast.makeText(getActivity(), "index is"+getShownIndex()+" && menu text is "+item.getTitle(), 1000).show();
        return super.onOptionsItemSelected(item);
    }*/
}
复制代码

 

3 将Fragment添加至Activity中

此时,已经实现了Activity和两个Fragment,将Fragment添加至Activity有两种方式。

3.1 在activity的layout文件中声明fragment

复制代码
<?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
       android:id="@+id/titles"
       android:layout_width="0px"
       android:layout_height="match_parent"
       android:layout_weight="0.31"
       class="com.fragment.TitlesFragment" />
   
   <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>
复制代码

3.2 在Activity中管理Fragment

在Activity中管理fragment, 需要使用FragmentManager. 通过调用activity的getFragmentManager()取得它的实例。

复制代码
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState); 
  setContentView(R.layout.main);

  FragmentManager fragmentManager = getFragmentManager();
  FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

  TitlesFragment titleFragment = new TitlesFragment();
  DetailsFragment detailsFragment = new DetailsFragment();
  fragmentTransaction.add(R.id.titles, titleFragment);
  fragmentTransaction.add(R.id.details, detailsFragment);
  fragmentTransaction.commit();
}
复制代码

 

效果图如下:

posted on 2014-09-04 08:57  qingchen1984  阅读(283)  评论(0编辑  收藏  举报

导航