Android Fragment

来源:互联网 发布:linux操作系统中文版 编辑:程序博客网 时间:2024/05/13 16:18

1.创建Fragment类

package com.jerry.todolist;import android.app.Activity;import android.app.Fragment;import android.os.Bundle;import android.view.KeyEvent;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.EditText;public class NewItemFragment extends Fragment {// 每个fragment应该封装它所提供的功能.定义一个接口,Activity通过实现接口监听新事项添加public interface OnNewItemAddListener {public void onNewItemAdd(String item);}// 创建一个变量来保存实现了该接口的Activity类的引用,一旦fragment绑定到了Activity,就可以通过// onAttach 获取该Activity的引用private OnNewItemAddListener onNewItemAddListener;@Overridepublic void onAttach(Activity activity) {super.onAttach(activity);//获取实现接口的activity的引用onNewItemAddListener = (OnNewItemAddListener) activity;}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {View view = inflater.inflate(R.layout.new_item_fragment, container,false);// 将view相关操作实现放到此// editTextfinal EditText myEditText = (EditText) view.findViewById(R.id.myEditText);myEditText.setOnKeyListener(new View.OnKeyListener() {@Overridepublic boolean onKey(View v, int keyCode, KeyEvent event) {if (event.getAction() == KeyEvent.ACTION_DOWN) {if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER|| keyCode == KeyEvent.KEYCODE_ENTER) {onNewItemAddListener.onNewItemAdd(myEditText.getText().toString());myEditText.setText("");return true;}}return false;}});return view;}}

2.定义fragment的布局:new_item_fragment.xml

<?xml version="1.0" encoding="UTF-8"?><EditText xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/myEditText"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:hint="@string/addItemHint" />

3.在需要用到fragment的布局文件中插入fragment标签

<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" >    <fragment        android:name="com.jerry.todolist.NewItemFragment"        android:id="@+id/newItemFragment"        android:layout_width="match_parent"        android:layout_height="wrap_content"        /><fragment    android:name="com.jerry.todolist.ToDoListFragment"    android:id="@+id/toDoListFragment"    android:layout_width="match_parent"    android:layout_height="wrap_content"    /></LinearLayout>

5.代码中获取fragment对象

FragmentManager fm = getFragmentManager();ToDoListFragment toDoListFragment = (ToDoListFragment) fm.findFragmentById(R.id.toDoListFragment);



原创粉丝点击