Fragment应用实例

创建Fragment需要实现三个方法

  • onCreate():系统创建Fragment对象回调后的方法,在实现代码中只初始化想要在Fragment中保持的必要组件,当Fragment被暂停或停止后可以恢复
  • onCreateView():当Fragment绘制界面组件时会回调该方法。该方法必须返回一个View,该View也就是该Fragment所显示的View
  • onPause():当用户离开该Fragment时将会回调该方法

开发显示图书详情的Fragment,涉及Fragment与Activity之间的通信

将Fragment添加到Activity中有如下两种方式

  • 在布局文件中使用<fragment.../>元素添加Fragment,<fragment.../>元素的android:name属性指定Fragment的实现类
  • 在java代码中通过FragmentTransaction对象的add()方法来添加Fragment

FragmentTransaction也被翻译为Fragment事务,与数据库事务类似的是,数据库事务代表了对底层数组的多个更新操作,而Fragment事务则代表了Activity对Fragment执行的多个操作的改变

通过FragmentManager来获得FragmentTransaction

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

图书类

BookContent.java
import android.content.Intent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BookContent {
    //定义一个内部类作为系统的业务对象
    public static class Book{
        public Integer id;
        public String title;
        public String desc;

        public Book(Integer id, String title, String desc) {
            this.id = id;
            this.title = title;
            this.desc = desc;
        }

        @Override
        public String toString() {
            return title;
        }
        //利用list集合记录系统包括的book对象
        public static List<Book> ITEMS=new ArrayList<Book>();
        //利用Map集合记录系统包括的book对象
        public static Map<Integer,Book> ITEM_MAP=new HashMap<Integer, Book>();
        static {
            //使用静态初始化代码。将Book对象添加到list集合、map集合中
            addItem(new Book(1,"呼啸山庄","英国女作家勃朗特姐妹之一艾米莉·勃朗特的作品"));
            addItem(new Book(2,"傲慢与偏见","英国女小说家简·奥斯汀创作的长篇小说"));
            addItem(new Book(3,"简爱","(英)夏洛蒂·勃朗特(Charlotte Bronte)原著"));
        }
        private static void addItem(Book book){
            ITEMS.add(book);
            ITEM_MAP.put(book.id,book);
        }
    }

}

左边显示图书列表

BookListFragment.java
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import androidx.annotation.Nullable;
import android.app.ListFragment;

public class BookListFragment extends ListFragment {
    private Callbacks mCallbacks;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //为该ListFragment设置Adapter
        setListAdapter(new ArrayAdapter<BookContent.Book>(getActivity(),android.R.layout.simple_list_item_activated_1,android.R.id.text1,BookContent.Book.ITEMS));

    }
    //当该Fragment被添加、显示到Activity时,回调该方法
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        //如果Activity没有实现Callbacks接口,抛出异常
        if(!(activity instanceof Callbacks)){
            throw new IllegalStateException("BookListFragment所在的Activity必须实现Callbacks接口");
        }
        //把该Activity当成Callbacks对象
        mCallbacks=(Callbacks) activity;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mCallbacks=null;
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        mCallbacks.onItemSelected(BookContent.Book.ITEMS.get(position).id);
    }

    public interface Callbacks{
        public void onItemSelected(Integer id);

    }
    public void setActivateOnItemClick(boolean activateOnItemClick){
        getListView().setChoiceMode(activateOnItemClick?ListView.CHOICE_MODE_SINGLE:ListView.CHOICE_MODE_NONE);
    }
}

右边显示图书细节详情

BookDetailFragment.java
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;

import android.app.Fragment;

public class BookDetailFragment extends Fragment {
    public static final String ITEM_ID = "item_id";
    //保存该fragment显示的book对象
    BookContent.Book book;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //如果启动该Fragment包含了ITEM_ID参数
        if (getArguments().containsKey(ITEM_ID)) {
            book = BookContent.Book.ITEM_MAP.get(getArguments().getInt(ITEM_ID));
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_book_detail, 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;
    }
}

显示fragment

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

import androidx.annotation.Nullable;
import android.app.Fragment;

public class Show extends Activity implements BookListFragment.Callbacks{
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bookshow);
    }

    @Override
    public void onItemSelected(Integer id) {
        //创建Bundle 向fragment传递参数
        Bundle arguments=new Bundle();
        arguments.putInt(BookDetailFragment.ITEM_ID,id);
        Fragment fragment=new BookDetailFragment();
        //向fragment传入参数
        fragment.setArguments(arguments);
        //使用fragment替换book_detail_container容器当前显示的Fragment
        getFragmentManager().beginTransaction().replace(R.id.book_detail_container,fragment).commit();

    }
}
fragment_book_detail.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="vertical">

    <TextView
        android:id="@+id/book_title"
        style="?android:attr/textAppearanceLarge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="16dp" />

    <TextView
        android:id="@+id/book_desc"
        style="?android:attr/textAppearanceMedium"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="16dp" />
</LinearLayout>
bookShow.xml
<?xml version="1.0" encoding="utf-8"?><!--定义一个水平排列的LinearLayout,并指定使用中等分隔条-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    android:divider="?android:attr/dividerHorizontal"
    android:orientation="horizontal"
    android:showDividers="middle">

    <fragment
        android:id="@+id/book_list"
        android:name="com.idsbg.foxconn.myapplication.BookListFragment"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent" />
<!--    添加一个Fragment容器-->
    <FrameLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3"
        android:id="@+id/book_detail_container" />
</LinearLayout>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值