Activity动态增加Fragment
生活随笔
收集整理的這篇文章主要介紹了
Activity动态增加Fragment
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
運行效果如下
整個程序分為兩部分:
1>第一部分NewItemFragment
效果如下:
1.1>布局文件如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"tools:context="com.demo.cxc.todolistfragment.NewItemFragment"><EditTextandroid:id="@+id/newItem_et"android:layout_width="0dp"android:layout_height="match_parent"android:layout_weight="1"android:hint="@string/new_item_hint"/><Buttonandroid:id="@+id/done_bt"android:text="@string/done_text"android:layout_width="wrap_content"android:layout_height="wrap_content" /> </LinearLayout>
1.2>代碼如下:
package com.demo.cxc.todolistfragment;import android.app.Activity; import android.net.Uri; import android.os.Bundle; import android.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText;public class NewItemFragment extends Fragment {private EditText newItem_et;private Button done_bt;//聲明一個接口實例,一旦Fragment保存綁定到了它的父Activity,就可以在OnAttach()中獲得該Activity的引用private OnNewItemAddedListener mListener;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// Inflate the layout for this fragmentView view= inflater.inflate(R.layout.fragment_new_item, container, false);newItem_et=(EditText)view.findViewById(R.id.newItem_et);done_bt=(Button) view.findViewById(R.id.done_bt);done_bt.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {mListener.onNewItemAdded(newItem_et.getText().toString());newItem_et.setText("");}});return view;}@Overridepublic void onAttach(Activity activity) {super.onAttach(activity);try {mListener = (OnNewItemAddedListener) activity;} catch (ClassCastException e) {//當該Fragment添加到Activity中時,當Activity沒有實現Fragment中聲明的接口時,會拋出該Exceptionthrow new ClassCastException(activity.toString()+ " must implement OnFragmentInteractionListener");}}@Overridepublic void onDetach() {super.onDetach();mListener = null;}/**Fragment通過該接口給其父Activity傳遞消息。* */public interface OnNewItemAddedListener {// TODO: Update argument type and namepublic void onNewItemAdded(String newItemString);}}
2.1>代碼如下:
package com.demo.cxc.todolistfragment;import android.app.Activity; import android.os.Bundle; import android.app.ListFragment; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView;import com.demo.cxc.todolistfragment.dummy.DummyContent;/*** A fragment representing a list of Items.*/ public class ItemListFragment extends ListFragment { } 其中ListFragment是Fragment的封裝類,可以通過綁定數據源呈現一個ListView作用它主要的UI展現方式。它提供了設置Adapter的方法,從而來使用各呈現列表條目。
3>MainActivity
3.1>布局如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:paddingBottom="@dimen/activity_vertical_margin"android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"tools:context=".MainActivity"><FrameLayoutandroid:id="@+id/newItem_container"android:layout_width="match_parent"android:layout_height="wrap_content"></FrameLayout><FrameLayoutandroid:id="@+id/itemList_container"android:layout_width="match_parent"android:layout_height="wrap_content"></FrameLayout><!--靜態包含--><!--<fragmentandroid:name="com.demo.cxc.todolistfragment.NewItemFragment"android:id="@+id/newItemFragment"android:layout_width="match_parent"android:layout_height="wrap_content"></fragment><fragmentandroid:name="com.demo.cxc.todolistfragment.ItemListFragment"android:id="@+id/itemListFragment"android:layout_width="match_parent"android:layout_height="wrap_content"></fragment>--></LinearLayout>
3.2>代碼如下:
package com.demo.cxc.todolistfragment;import android.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.ArrayAdapter;import java.util.ArrayList;public class MainActivity extends ActionBarActivity implements NewItemFragment.OnNewItemAddedListener {private static final String NEW_ITEM_FRAGMENT_TAG = "new_item_fragment_tag";private static final String ITEM_LIST_FRAGMENT_TAG = "item_list_fragment_tag";private ItemListFragment itemListFragment;private FragmentManager fragmentManager;private ArrayList<String> newItems;private ArrayAdapter<String> arrayAdapter;private void initViews() {fragmentManager = getFragmentManager();FragmentTransaction ft = fragmentManager.beginTransaction();/*往容器newItem_container里添加Fragment*///add時未指定Tag,則要想得到該Fragment的引用時,可以使用fragmentManage.findFragmentById(R.id.newItem_container);ft.add(R.id.newItem_container, new NewItemFragment());/*add時指定Tag,則要想得到該Fragment的引用時,1>可以使用fragmentManage.findFragmentById(R.id.newItem_container);2>也可以使用fragmentManage.findFragmentByTag(NEW_ITEM_FRAGMENT_TAG);*/ // ft.add(R.id.newItem_container, new NewItemFragment(), NEW_ITEM_FRAGMENT_TAG);/*往容器itemList_container里添加Fragment*///add時未指定Tag,則要想得到該Fragment的引用時,可以使用fragmentManage.findFragmentById(R.id.itemList_container);ft.add(R.id.itemList_container, new ItemListFragment());/*add時指定Tag,則要想得到該Fragment的引用時,1>可以使用fragmentManage.findFragmentById(R.id.itemList_container);2>也可以使用fragmentManage.findFragmentByTag(ITEM_LIST_FRAGMENT_TAG);*/ // ft.add(R.id.itemList_container, new ItemListFragment(), ITEM_LIST_FRAGMENT_TAG);ft.commit();newItems = new ArrayList<String>();arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, newItems);}@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initViews();}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.menu_main, menu);return true;}@Overrideprotected void onResume() {super.onResume();/** 如果在onCreate()方法中查找Fragment,會返回Null.* 因為此時,布局還沒有加載完全,所以就把查找工作放在這里。* *///方法一:通過父容器的id查找該FragmentitemListFragment = (ItemListFragment) fragmentManager.findFragmentById(R.id.itemList_container);//方法二:通過add 時指定的Tag 來查找該Fragment // itemListFragment = (ItemListFragment) fragmentManager.findFragmentByTag(ITEM_LIST_FRAGMENT_TAG);if (itemListFragment != null) {itemListFragment.setListAdapter(arrayAdapter);} else {Log.i("CXC", "----------NULL--------------");}}@Overridepublic void onNewItemAdded(String newItemString) {newItems.add(0, newItemString);arrayAdapter.notifyDataSetChanged();} }
總結
以上是生活随笔為你收集整理的Activity动态增加Fragment的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Interface classes
- 下一篇: 两个有序线性表的合并(线性表使用 Vec