您的位置:首页 > 移动开发 > Android开发

FragmentTest学习笔记2

2014-03-08 10:44 423 查看


1.Activity 与Fragment之间的数据传输






(1)      Activity向Fragment传递数据

API注释:

Fragment

public void setArguments(Bundle args)

Supplythe construction arguments for this fragment. Thiscan only be called before the fragment has been attached to its activity; thatis, you should call it immediately after constructing the fragment. Thearguments supplied here will be
retained across fragment destroy and creation.

public final Bundle getArguments () 

Returnthe arguments supplied-- when the fragment wasinstantiated, if any.

(2)      Fragment向Activity传递数据:

例子:将列表选中的id 传给Activity

【Fragment所在的类】

public classBookListFragment extends ListFragment {

         //定义一个回调接口 该Fragment对象所在Activity需要实现该接口

         publicinterface Callbacks{

                   publicvoid onItemSelected(Integer id);

         }

 

  @Override
    //当用户单击某列表项时回调该方法(让该回调方法依附于该Fragment的一个事件操作的响应函数)
    public
void
onListItemClick(ListView l, View v, int position,long id){
       super.onListItemClick(l, v, position, id);
       //激发mCallbacks的onItemSelected方法
       mCallbacks.onItemSelected(BookContent.ITEMS.get(position).id);
    }

}

【Activity所在的类】

public
class
SelectBookActivity extends Activityimplements BookListFragment.Callbacks{
    @Override
    public
void
onCreate(Bundle savedInstanceState){}
    //implement the method from interface BookListFragment.Callbacks
    public voidonItemSelected(Integer id){}

}

 

2.两个Fragment的创建

《1》BookDetailFragmet






【Activity向Fragment传输数据】:

 








《2》BookListFragment



//extends ListFragMent
public
class
BookListFragment extends ListFragment {

@Override
    public
void
onCreate(Bundle savedInstanceState){
       super.onCreate(savedInstanceState);
       //为该ListFragment设置Adapter
       ArrayAdapter<BookContent.Book> adapter = newArrayAdapter<BookContent.Book>(
              getActivity(),android.R.layout.simple_list_item_activated_1,
              android.R.id.text1,BookContent.ITEMS);
       setListAdapter(adapter);
    }

}

 
3.执行路线:



(1)
<activity
   android:name="com.example.bookdetailfragment.SelectBookActivity"
           android:label="@string/app_name">
            <intent-filter>
                <actionandroid:name="android.intent.action.MAIN"/>
                <categoryandroid:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
       </activity>

(2)class SelectBookActivity{

setContentView(R.layout.activity_book_twopane);

}

(3)R.layout.activity_book_twopane.xml

<fragment
        android:name="com.example.bookdetailfragment.BookListFragment"

(4)classBookListFragment{

//当用户单击某列表项时回调该方法
    public
void
onListItemClick(ListView l, View v, int position,long id){
       super.onListItemClick(l, v, position, id);
       //激发mCallbacks的onItemSelected方法
       mCallbacks.onItemSelected(BookContent.ITEMS.get(position).id);
    }

}

(5) public classSelectBookActivity{

Bundle arguments = new Bundle();
arguments.putInt(BookDetailFragment.ITEM_ID, id);

BookDetailFragmentbookdetailfragment = new BookDetailFragment();
bookdetailfragment.setArguments(arguments);//<---向Fragment传入参数

}

(6)

public class BookDetailFragment{

  public
void onCreate
(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(getArguments().containsKey(ITEM_ID)){
                  //--如果启动该Fragment时包含了ITEM_ID参数
book = BookContent.ITEM_MAP.get(getArguments().getInt(ITEM_ID));   
        }
    }
    @Override
    public View   onCreateView(LayoutInflaterinflater, ViewGroup container,
        BundlesavedInstanceState){
    //加载布局文件
    ViewrootView = inflater.inflate(R.layout.activity_book_detail_fragment,
            container,false);
    if(book!=null){
((TextView)rootView.findViewById(R.id.book_title)).setText(book.title
((TextView)rootView.findViewById(R.id.book_title)).setText(book.desc)
    return rootView;
}
}

4.其他问题:
(0)Fragment管理与Fragment事务 

FragmentManager负责Fragment管理,FragmentTransaction负责Fragment事务。





(1)inflater.inflate()函数的分析
public abstract class LayoutInflater
public View inflate (XmlPullParser parser, ViewGroup root,boolean
attachToRoot)

Inflate a new view hierarchyfrom the specified XML node.
Parameters
parser XML domnode containing the description of the view hierarchy.
root   Optionalview to be the parent of the generated hierarchy (ifattachToRoot is true), or else simply an object that provides a set ofLayoutParams values
for root of the returned hierarchy (if attachToRoot is false.)

 
 
@Override
    public View    onCreateView(LayoutInflaterinflater, ViewGroupcontainer, Bundle
savedInstanceState){
    //加载布局文件
    ViewrootView =
inflater.inflate(R.layout.activity_book_detail_fragment,
            container,false);
    if(book!=null){
       
((TextView)rootView.findViewById(R.id.book_title)).setText(book.title);
((TextView)rootView.findViewById(R.id.book_desc)).setText(book.desc);
  }
    return rootView;
}
详细分析可以参考:
http://blog.csdn.net/zuolongsnail/article/details/6370035

(2)ArrayAdapter

ArrayAdapter<BookContent.Book>adapter =new ArrayAdapter<BookContent.Book>(getActivity(),android.R.layout.simple_list_item_activated_1,android.R.id.text1,BookContent.ITEMS);//左边的Fragment 此处只显示文字
API原型:
public ArrayAdapter (Context context, intresource, int textViewResourceId, List<T> objects)

Constructor

 

Parameters

context    Thecurrent context.

resource  Theresource ID for a layout file containing a layout to use when instantiatingviews.

textViewResourceId        The id of the TextView within the layout resource to bepopulated

objects     Theobjects to represent in the ListView.

 
getActivity():



simple_list_item_activated_1:
(from R.layout extendsObject
http://developer.android.com/reference/android/R.layout.html


单字符串单行显示,simple_list_item_1,

双字符串双行显示,simple_list_item_2

simple_list_item_activated_1         :

A version of simple_list_item_1 that isable to change its background state to indicatewhen it is activated (that is checked by a ListView).

android.R.id.text1
参见源码:

<TextViewxmlns:android="http://schemas.android.com/apk/res/android"

    android:id="@android:id/text1"   <-----------HERE

   android:layout_width="fill_parent"

   android:layout_height="?android:attr/listPreferredItemHeight"

   android:textAppearance="?android:attr/textAppearanceLarge"

    android:gravity="center_vertical"

    android:paddingLeft="5dip"

    android:singleLine="true"

/>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android Fragment