# 5.2.5 Fragment實例精講——新聞(購物)類App列表Fragment的簡單實現
## 本節引言:
> 相信大家對點擊列表,然后進入詳情這種App并不陌生吧,在購物類App和新聞類App中最為常見: 下面我們簡單來講一下流程邏輯!
## 1.邏輯流程講解:
剛好公司測試妹子的測試機上裝了楚楚街9塊9的APP,呵呵,直接就照這個來研究吧:

嘿嘿,市面上很多APP都是這種樣子的,而這個可以用我們學到的Fragment來實現: 可能gif動畫看不清,筆者用界面原型工具畫個大概吧:

大概就這樣,中間區域是一個布局容器,一般是FrameLayout,然后我們將一個Fragment replace 到這個容器中或者add也行,而這個Fragment中有一個listview,當我們點擊這個ListView中的一項, 中間容器中的Fragment就會被replace成對應詳細信息的Fragment所替代,如果我們只是replace的話, 就不會保存第一個Fragment的狀態,用戶又得從頭開始瀏覽,這肯定是很不方便的,這里我們可以 通過Fragment棧的addtobackStack和popbackstack來解決這個問題!當replace的同時,我們將被替換 的Fragment添加到stack中,當用戶點擊回退按鈕時,調用popbackstack彈出棧,具體實現見下述代碼 示例!
## 2.代碼示例:簡單新聞類APP列表和內容切換的實現
**運行效果圖**:

**實現代碼**:
**Step 1**:先把兩個Fragment以及Activity的布局實現了
**fg_newlist.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:background="@color/white"
android:orientation="horizontal">
<ListView
android:id="@+id/list_news"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
```
**fg_context.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/txt_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textColor="@color/blue"
android:textSize="20sp" />
</LinearLayout>
```
**activity_main.xml**:
```
<RelativeLayout 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"
tools:context=".MainActivity">
<TextView
android:id="@+id/txt_title"
android:layout_width="match_parent"
android:layout_height="56dp"
android:background="@color/blue"
android:textColor="@color/white"
android:text="新聞列表"
android:textSize="20sp"
android:textStyle="bold"
android:gravity="center"/>
<FrameLayout
android:id="@+id/fl_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/txt_title"/>
</RelativeLayout>
```
**Step 2**:實現我們的業務Bean類和自定義BaseAdapter類:
**Data.java:**
```
/**
* Created by Jay on 2015/9/6 0006.
*/
public class Data {
private String new_title;
private String new_content;
public Data(){}
public Data(String new_title, String new_content) {
this.new_title = new_title;
this.new_content = new_content;
}
public String getNew_title() {
return new_title;
}
public String getNew_content() {
return new_content;
}
public void setNew_title(String new_title) {
this.new_title = new_title;
}
public void setNew_content(String new_content) {
this.new_content = new_content;
}
}
```
**MyAdapter.java**:
```
/**
* Created by Jay on 2015/9/6 0006.
*/
public class MyAdapter extends BaseAdapter{
private List<Data> mData;
private Context mContext;
public MyAdapter(List<Data> mData, Context mContext) {
this.mData = mData;
this.mContext = mContext;
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView == null){
convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item,parent,false);
viewHolder = new ViewHolder();
viewHolder.txt_item_title = (TextView) convertView.findViewById(R.id.txt_item_title);
convertView.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.txt_item_title.setText(mData.get(position).getNew_title());
return convertView;
}
private class ViewHolder{
TextView txt_item_title;
}
}
```
**Step 3**:MainActivity的實現
**MainActivity.java**:
```
public class MainActivity extends AppCompatActivity {
private TextView txt_title;
private FrameLayout fl_content;
private Context mContext;
private ArrayList<Data> datas = null;
private FragmentManager fManager = null;
private long exitTime = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = MainActivity.this;
fManager = getFragmentManager();
bindViews();
datas = new ArrayList<Data>();
for (int i = 1; i <= 20; i++) {
Data data = new Data("新聞標題" + i, i + "~新聞內容~~~~~~~~");
datas.add(data);
}
NewListFragment nlFragment = new NewListFragment(fManager, datas);
FragmentTransaction ft = fManager.beginTransaction();
ft.replace(R.id.fl_content, nlFragment);
ft.commit();
}
private void bindViews() {
txt_title = (TextView) findViewById(R.id.txt_title);
fl_content = (FrameLayout) findViewById(R.id.fl_content);
}
//點擊回退鍵的處理:判斷Fragment棧中是否有Fragment
//沒,雙擊退出程序,否則像是Toast提示
//有,popbackstack彈出棧
@Override
public void onBackPressed() {
if (fManager.getBackStackEntryCount() == 0) {
if ((System.currentTimeMillis() - exitTime) > 2000) {
Toast.makeText(getApplicationContext(), "再按一次退出程序",
Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
super.onBackPressed();
}
} else {
fManager.popBackStack();
txt_title.setText("新聞列表");
}
}
}
```
**Step 4**:列表Fragment的實現:
**NewListFragment.java**:
```
package com.jay.fragmentdemo4;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Jay on 2015/9/6 0006.
*/
public class NewListFragment extends Fragment implements AdapterView.OnItemClickListener {
private FragmentManager fManager;
private ArrayList<Data> datas;
private ListView list_news;
public NewListFragment(FragmentManager fManager, ArrayList<Data> datas) {
this.fManager = fManager;
this.datas = datas;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fg_newlist, container, false);
list_news = (ListView) view.findViewById(R.id.list_news);
MyAdapter myAdapter = new MyAdapter(datas, getActivity());
list_news.setAdapter(myAdapter);
list_news.setOnItemClickListener(this);
return view;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FragmentTransaction fTransaction = fManager.beginTransaction();
NewContentFragment ncFragment = new NewContentFragment();
Bundle bd = new Bundle();
bd.putString("content", datas.get(position).getNew_content());
ncFragment.setArguments(bd);
//獲取Activity的控件
TextView txt_title = (TextView) getActivity().findViewById(R.id.txt_title);
txt_title.setText(datas.get(position).getNew_content());
//加上Fragment替換動畫
fTransaction.setCustomAnimations(R.anim.fragment_slide_left_enter, R.anim.fragment_slide_left_exit);
fTransaction.replace(R.id.fl_content, ncFragment);
//調用addToBackStack將Fragment添加到棧中
fTransaction.addToBackStack(null);
fTransaction.commit();
}
}
```
**Step 5**:內容Fragment的實現:
**NewContentFragment.java**:
```
/**
* Created by Jay on 2015/9/6 0006.
*/
public class NewContentFragment extends Fragment {
NewContentFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fg_content, container, false);
TextView txt_content = (TextView) view.findViewById(R.id.txt_content);
//getArgument獲取傳遞過來的Bundle對象
txt_content.setText(getArguments().getString("content"));
return view;
}
}
```
代碼很簡單,就不慢慢解釋了~
## 3.代碼下載
**FragmentDemo5.zip**:[下載 FragmentDemo5.zip](/try/download/FragmentDemo5.zip)
## 本節小結:
> 因為時間的關系,并沒有詳細的去做過多的講解,示例代碼也很簡單,方便各位初學者理解! 如果要用到實際項目中還需要對此進行一番修改~!好的,本節就到這里,謝謝~
- 1.0 Android基礎入門教程
- 1.0.1 2015年最新Android基礎入門教程目錄
- 1.1 背景相關與系統架構分析
- 1.2 開發環境搭建
- 1.2.1 使用Eclipse + ADT + SDK開發Android APP
- 1.2.2 使用Android Studio開發Android APP
- 1.3 SDK更新不了問題解決
- 1.4 Genymotion模擬器安裝
- 1.5.1 Git使用教程之本地倉庫的基本操作
- 1.5.2 Git之使用GitHub搭建遠程倉庫
- 1.6 .9(九妹)圖片怎么玩
- 1.7 界面原型設計
- 1.8 工程相關解析(各種文件,資源訪問)
- 1.9 Android程序簽名打包
- 1.11 反編譯APK獲取代碼&資源
- 2.1 View與ViewGroup的概念
- 2.2.1 LinearLayout(線性布局)
- 2.2.2 RelativeLayout(相對布局)
- 2.2.3 TableLayout(表格布局)
- 2.2.4 FrameLayout(幀布局)
- 2.2.5 GridLayout(網格布局)
- 2.2.6 AbsoluteLayout(絕對布局)
- 2.3.1 TextView(文本框)詳解
- 2.3.2 EditText(輸入框)詳解
- 2.3.3 Button(按鈕)與ImageButton(圖像按鈕)
- 2.3.4 ImageView(圖像視圖)
- 2.3.5.RadioButton(單選按鈕)&Checkbox(復選框)
- 2.3.6 開關按鈕ToggleButton和開關Switch
- 2.3.7 ProgressBar(進度條)
- 2.3.8 SeekBar(拖動條)
- 2.3.9 RatingBar(星級評分條)
- 2.4.1 ScrollView(滾動條)
- 2.4.2 Date & Time組件(上)
- 2.4.3 Date & Time組件(下)
- 2.4.4 Adapter基礎講解
- 2.4.5 ListView簡單實用
- 2.4.6 BaseAdapter優化
- 2.4.7ListView的焦點問題
- 2.4.8 ListView之checkbox錯位問題解決
- 2.4.9 ListView的數據更新問題
- 2.5.0 構建一個可復用的自定義BaseAdapter
- 2.5.1 ListView Item多布局的實現
- 2.5.2 GridView(網格視圖)的基本使用
- 2.5.3 Spinner(列表選項框)的基本使用
- 2.5.4 AutoCompleteTextView(自動完成文本框)的基本使用
- 2.5.5 ExpandableListView(可折疊列表)的基本使用
- 2.5.6 ViewFlipper(翻轉視圖)的基本使用
- 2.5.7 Toast(吐司)的基本使用
- 2.5.8 Notification(狀態欄通知)詳解
- 2.5.9 AlertDialog(對話框)詳解
- 2.6.0 其他幾種常用對話框基本使用
- 2.6.1 PopupWindow(懸浮框)的基本使用
- 2.6.2 菜單(Menu)
- 2.6.3 ViewPager的簡單使用
- 2.6.4 DrawerLayout(官方側滑菜單)的簡單使用
- 3.1.1 基于監聽的事件處理機制
- 3.2 基于回調的事件處理機制
- 3.3 Handler消息傳遞機制淺析
- 3.4 TouchListener PK OnTouchEvent + 多點觸碰
- 3.5 監聽EditText的內容變化
- 3.6 響應系統設置的事件(Configuration類)
- 3.7 AnsyncTask異步任務
- 3.8 Gestures(手勢)
- 4.1.1 Activity初學乍練
- 4.1.2 Activity初窺門徑
- 4.1.3 Activity登堂入室
- 4.2.1 Service初涉
- 4.2.2 Service進階
- 4.2.3 Service精通
- 4.3.1 BroadcastReceiver牛刀小試
- 4.3.2 BroadcastReceiver庖丁解牛
- 4.4.2 ContentProvider再探——Document Provider
- 4.5.1 Intent的基本使用
- 4.5.2 Intent之復雜數據的傳遞
- 5.1 Fragment基本概述
- 5.2.1 Fragment實例精講——底部導航欄的實現(方法1)
- 5.2.2 Fragment實例精講——底部導航欄的實現(方法2)
- 5.2.3 Fragment實例精講——底部導航欄的實現(方法3)
- 5.2.4 Fragment實例精講——底部導航欄+ViewPager滑動切換頁面
- 5.2.5 Fragment實例精講——新聞(購物)類App列表Fragment的簡單實現
- 6.1 數據存儲與訪問之——文件存儲讀寫
- 6.2 數據存儲與訪問之——SharedPreferences保存用戶偏好參數
- 6.3.1 數據存儲與訪問之——初見SQLite數據庫
- 6.3.2 數據存儲與訪問之——又見SQLite數據庫
- 7.1.1 Android網絡編程要學的東西與Http協議學習
- 7.1.2 Android Http請求頭與響應頭的學習
- 7.1.3 Android HTTP請求方式:HttpURLConnection
- 7.1.4 Android HTTP請求方式:HttpClient
- 7.2.1 Android XML數據解析
- 7.2.2 Android JSON數據解析
- 7.3.1 Android 文件上傳
- 7.3.2 Android 文件下載(1)
- 7.3.3 Android 文件下載(2)
- 7.4 Android 調用 WebService
- 7.5.1 WebView(網頁視圖)基本用法
- 7.5.2 WebView和JavaScrip交互基礎
- 7.5.3 Android 4.4后WebView的一些注意事項
- 7.5.4 WebView文件下載
- 7.5.5 WebView緩存問題
- 7.5.6 WebView處理網頁返回的錯誤碼信息
- 7.6.1 Socket學習網絡基礎準備
- 7.6.2 基于TCP協議的Socket通信(1)
- 7.6.3 基于TCP協議的Socket通信(2)
- 7.6.4 基于UDP協議的Socket通信
- 8.1.1 Android中的13種Drawable小結 Part 1
- 8.1.2 Android中的13種Drawable小結 Part 2
- 8.1.3 Android中的13種Drawable小結 Part 3
- 8.2.1 Bitmap(位圖)全解析 Part 1
- 8.2.2 Bitmap引起的OOM問題
- 8.3.1 三個繪圖工具類詳解
- 8.3.2 繪圖類實戰示例
- 8.3.3 Paint API之—— MaskFilter(面具)
- 8.3.4 Paint API之—— Xfermode與PorterDuff詳解(一)
- 8.3.5 Paint API之—— Xfermode與PorterDuff詳解(二)
- 8.3.6 Paint API之—— Xfermode與PorterDuff詳解(三)
- 8.3.7 Paint API之—— Xfermode與PorterDuff詳解(四)
- 8.3.8 Paint API之—— Xfermode與PorterDuff詳解(五)
- 8.3.9 Paint API之—— ColorFilter(顏色過濾器)(1/3)
- 8.3.10 Paint API之—— ColorFilter(顏色過濾器)(2-3)
- 8.3.11 Paint API之—— ColorFilter(顏色過濾器)(3-3)
- 8.3.12 Paint API之—— PathEffect(路徑效果)
- 8.3.13 Paint API之—— Shader(圖像渲染)
- 8.3.14 Paint幾個枚舉/常量值以及ShadowLayer陰影效果
- 8.3.15 Paint API之——Typeface(字型)
- 8.3.16 Canvas API詳解(Part 1)
- 8.3.17 Canvas API詳解(Part 2)剪切方法合集
- 8.3.18 Canvas API詳解(Part 3)Matrix和drawBitmapMash
- 8.4.1 Android動畫合集之幀動畫
- 8.4.2 Android動畫合集之補間動畫
- 8.4.3 Android動畫合集之屬性動畫-初見
- 8.4.4 Android動畫合集之屬性動畫-又見
- 9.1 使用SoundPool播放音效(Duang~)
- 9.2 MediaPlayer播放音頻與視頻
- 9.3 使用Camera拍照
- 9.4 使用MediaRecord錄音
- 10.1 TelephonyManager(電話管理器)
- 10.2 SmsManager(短信管理器)
- 10.3 AudioManager(音頻管理器)
- 10.4 Vibrator(振動器)
- 10.5 AlarmManager(鬧鐘服務)
- 10.6 PowerManager(電源服務)
- 10.7 WindowManager(窗口管理服務)
- 10.8 LayoutInflater(布局服務)
- 10.9 WallpaperManager(壁紙管理器)
- 10.10 傳感器專題(1)——相關介紹
- 10.11 傳感器專題(2)——方向傳感器
- 10.12 傳感器專題(3)——加速度/陀螺儀傳感器
- 10.12 傳感器專題(4)——其他傳感器了解
- 10.14 Android GPS初涉
- 11.0《2015最新Android基礎入門教程》完結散花~