Android Fragment学习笔记(二)

本文介绍了Android中Fragment之间的通信方式,通过实例演示了如何在两个Fragment间进行数据传递,实现用户选择项在不同Fragment间的展示。具体展示了三个关键文件的作用,包括Fragment布局设置、详情Fragment的创建与视图生成、标题Fragment的初始化与详情显示逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

点击打开链接

Android Fragment学习笔记(二)

分类: Android 控件 1505人阅读 评论(7) 收藏 举报

       Note:本例有两个Fragment,并且Fragment之间能够进行通信,每当点击左边fragment的item时,都会在右边的fragment中显示对应的内容。需要整个工程的请到我的资源里下载fragmentlayou123.

本程序涉及3个.java文件:Fragmentlayout123Activity.java、DetailsFragment.java、TitleFragment.java。其中各个部分的功能如下:

1、在Fragmentlayout123Activity.java中,设置了fragment_layout布局,并建了一个DetailsActivity,用在手机上显示。

  1. public class Fragmentlayout123Activity extends Activity {  
  2.         protected void onCreate(Bundle savedInstanceState) {  
  3.             super.onCreate(savedInstanceState);  
  4.             setContentView(R.layout.fragment_layout);  
  5.         }  
  6.         /** 
  7.          * This is a secondary activity, to show what the user has selected 
  8.          * when the screen is not large enough to show it all in one activity. 
  9.          */  
  10.         public class DetailsActivity extends Activity {  
  11.             @Override  
  12.             protected void onCreate(Bundle savedInstanceState) {  
  13.                 super.onCreate(savedInstanceState);  
  14.   
  15.                 if (getResources().getConfiguration().orientation  
  16.                         == Configuration.ORIENTATION_LANDSCAPE) {  
  17.                     // If the screen is now in landscape mode, we can show the  
  18.                     // dialog in-line with the list so we don't need this activity.  
  19.                     finish();  
  20.                     return;  
  21.                 }  
  22.                 if (savedInstanceState == null) {  
  23.                     // During initial setup, plug in the details fragment.  
  24.                     DetailsFragment details = new DetailsFragment();  
  25.                     details.setArguments(getIntent().getExtras());  
  26.                     getFragmentManager().beginTransaction().add(android.R.id.content, details).commit();  
  27.                 }  
  28.             }  
  29.         }  
  30.     }  

2、在DetailsFragment.java中,方法newInstance用于新建一个DetailFragment,onCreateView用来产生DetailFragment的View。

  1. public class DetailsFragment extends Fragment {  
  2.     /**Create a new instance of DetailsFragment, initialized to show the text at 'index'.*/  
  3.     public static DetailsFragment newInstance(int index) {  
  4.         DetailsFragment f = new DetailsFragment();  
  5.         // Supply index input as an argument.  
  6.         Bundle args = new Bundle();  
  7.         args.putInt("index", index);  
  8.         //给Fragment初始化参数  
  9.         f.setArguments(args);  
  10.         return f;  
  11.     }  
  12.     public int getShownIndex() {  
  13.         return getArguments().getInt("index"0);  
  14.     }  
  15.     @Override  
  16.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
  17.             Bundle savedInstanceState) {  
  18.         if (container == null) {  
  19.             // We have different layouts, and in one of them this  
  20.             // fragment's containing frame doesn't exist. The fragment  
  21.             // may still be created from its saved state, but there is  
  22.             // no reason to try to create its view hierarchy because it  
  23.             // won't be displayed. Note this is not needed -- we could  
  24.             // just run the code below, where we would create and return  
  25.             // the view hierarchy; it would just never be used.  
  26.             return null;  
  27.         }  
  28.   
  29.         ScrollView scroller = new ScrollView(getActivity());  
  30.         TextView text = new TextView(getActivity());  
  31.         int padding = (int) TypedValue.applyDimension(  
  32.                 TypedValue.COMPLEX_UNIT_DIP, 4, getActivity().getResources()  
  33.                         .getDisplayMetrics());  
  34.         // hetao:设置边框大小  
  35.         text.setPadding(padding, padding, padding, padding);  
  36.         scroller.addView(text);  
  37.         text.setText(DIALOGUE[getShownIndex()]);  
  38.         return scroller;  
  39.     }  
  40.     public static final String[] DIALOGUE = {  
  41.             "So shaken as we are, so wan with care,"  
  42.                     + "In forwarding this dear expedience.",  
  43.   
  44.             "Hear him but reason in divinity,"  
  45.                     + "From open haunts and popularity.",  
  46.   
  47.             "I come no more to make you laugh: things now,"  
  48.                     + "A man may weep upon his wedding-day.",  
  49.   
  50.             "First, heaven be the record to my speech!"  
  51.                     + "What my tongue speaks my right drawn sword may prove.",  
  52.   
  53.             "Now is the winter of our discontent"  
  54.                     + "Clarence comes.",  
  55.   
  56.             "To bait fish withal: if it will feed nothing else,"  
  57.                     + "will better the instruction.",  
  58.   
  59.             "Virtue! a fig! 'tis in ourselves that we are thus"  
  60.                     + "you call love to be a sect or scion.",  
  61.   
  62.             "Blow, winds, and crack your cheeks! rage! blow!"};  
  63.     public static final String[] TITLES = { "Henry IV (1)""Henry V",  
  64.             "Henry VIII""Richard II""Richard III""Merchant of Venice",  
  65.             "Othello""King Lear" };  
  66. }  

3、在TitleFragment.java中,onActivityCreated用来初始化TitleFragment,showDetails用来显示选中Item的内容。

  1. public class TitlesFragment extends ListFragment {  
  2.     boolean mDualPane;  //检验是否有DetailFragment,没有就另起一个activity  
  3.     int mCurCheckPosition = 0;  
  4.   
  5.     @Override  
  6.   //初始化TitleFragment  
  7.     public void onActivityCreated(Bundle savedInstanceState) {  
  8.         super.onActivityCreated(savedInstanceState);  
  9.         // Populate list with our static array of titles.  
  10.         setListAdapter(new ArrayAdapter<String>(getActivity(),  
  11.                 android.R.layout.simple_list_item_activated_1, TITLES));  
  12.         // Check to see if we have a frame in which to embed the details  
  13.         // fragment directly in the containing UI.  
  14.         View detailsFrame = getActivity().findViewById(R.id.details);  
  15.         mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;  
  16.   
  17.         if (savedInstanceState != null) {  
  18.             // Restore last state for checked position.  
  19.             mCurCheckPosition = savedInstanceState.getInt("curChoice"0);  
  20.         }  
  21.   
  22.         if (mDualPane) {  
  23.             // In dual-pane mode, the list view highlights the selected item.  
  24.             getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);  
  25.             // Make sure our UI is in the correct state.  
  26.             showDetails(mCurCheckPosition);  
  27.         }  
  28.     }  
  29.   
  30.     @Override  
  31.     public void onSaveInstanceState(Bundle outState) {  
  32.         super.onSaveInstanceState(outState);  
  33.         outState.putInt("curChoice", mCurCheckPosition);  
  34.     }  
  35.   
  36.     @Override  
  37.     public void onListItemClick(ListView l, View v, int position, long id) {  
  38.         showDetails(position);  
  39.     }  
  40.   
  41.     /** 
  42.      * Helper function to show the details of a selected item, either by 
  43.      * displaying a fragment in-place in the current UI, or starting a 
  44.      * whole new activity in which it is displayed. 
  45.      */  
  46.     void showDetails(int index) {  
  47.         mCurCheckPosition = index;  
  48.   
  49.         if (mDualPane) {  
  50.             // We can display everything in-place with fragments, so update  
  51.             // the list to highlight the selected item and show the data.  
  52.             getListView().setItemChecked(index, true);  
  53.   
  54.             // Check what fragment is currently shown, replace if needed.  
  55.             DetailsFragment details = (DetailsFragment)  
  56.                     getFragmentManager().findFragmentById(R.id.details);  
  57.             if (details == null || details.getShownIndex() != index) {  
  58.                 details = DetailsFragment.newInstance(index);  
  59.   
  60.                 // Execute a transaction, replacing any existing fragment  
  61.                 // with this one inside the frame.  
  62.                 FragmentTransaction ft = getFragmentManager().beginTransaction();  
  63.                 ft.replace(R.id.details, details);  
  64.                 ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);  
  65.                 ft.commit();  
  66.             }  
  67.   
  68.         } else {  
  69.             // Otherwise we need to launch a new activity to display  
  70.             // the dialog fragment with selected text.  
  71.             Intent intent = new Intent();  
  72.             intent.setClass(getActivity(), DetailsActivity.class);  
  73.             intent.putExtra("index", index);  
  74.             startActivity(intent);  
  75.         }  
  76.     }  
  77.     //copied by hetao  
  78.     public static final String[] TITLES =   
  79.     {  
  80.             "Henry IV (1)",     
  81.             "Henry V",  
  82.             "Henry VIII",         
  83.             "Richard II",  
  84.             "Richard III",  
  85.             "Merchant of Venice",    
  86.             "Othello",  
  87.             "King Lear"  
  88.     };  
  89.   
  90. }  

其中还涉及到一个布局文件fragment_layout.xml

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:orientation="horizontal" android:layout_width="match_parent"  
  3.     android:layout_height="match_parent">  
  4.     <fragment class="haha.com.cn.TitlesFragment"  
  5.         android:id="@+id/titles" android:layout_weight="1"  
  6.         android:layout_width="0px" android:layout_height="match_parent"   
  7.         />  
  8.     <FrameLayout android:id="@+id/details"  
  9.         android:layout_weight="1" android:layout_width="0px"  
  10.         android:layout_height="match_parent"   
  11.         android:background="?android:attr/detailsElementBackground" />  
  12. </LinearLayout>  


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值