Easy Tutorial
❮ Android Tutorial Smsmanager Fastjson Intro ❯

5.2.5 Fragment Example - News (Shopping) App List Fragment Simple Implementation

Category Android Basic Tutorial

Introduction to This Section:

>

I believe everyone is familiar with the app that allows you to click on a list and then enter the details, which is most common in shopping and news apps: Let's briefly talk about the process logic!


1. Process Logic Explanation:

The test girl in our company has an app called "ChuChu Street 9.9" on her test machine, haha, let's just study this one directly:

Hehe, many apps on the market are like this, and this can be implemented with the Fragment we have learned: The gif animation may not be clear, and the author has drawn a rough sketch with the interface prototype tool:

It's roughly like this, the middle area is a layout container, usually a FrameLayout, and then we will replace a Fragment into this container or add it, and this Fragment contains a listview. When we click on an item in this ListView, the Fragment in the middle container will be replaced by the corresponding detailed information Fragment. If we only replace it, the state of the first Fragment will not be saved, and the user will have to start browsing from the beginning, which is definitely very inconvenient. Here we can solve this problem by adding the Fragment to the stack with addtobackStack and popbackstack of the Fragment stack! When replacing, we add the replaced Fragment to the stack, and when the user clicks the back button, call popbackstack to pop the stack, and the specific implementation can be seen in the following code example!


2. Code Example: Simple Implementation of News App List and Content Switching

Running Effect Picture :

Implementation Code :

Step 1 : First, implement the layout of the two Fragments and 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="News List"
        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 : Implement our business Bean class and custom BaseAdapter class:

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
```java
Data data = new Data("News Title" + i, i + "~News Content~~~~~~~~");
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);
}
// Handling the back button press: Determine if there is a Fragment in the Fragment stack
// If not, double click to exit the program, otherwise it's like a Toast prompt
// If yes, popbackstack pops up the stack
@Override
public void onBackPressed() {
    if (fManager.getBackStackEntryCount() == 0) {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(getApplicationContext(), "Press again to exit the program",
                    Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            super.onBackPressed();
        }
    } else {
        fManager.popBackStack();
        txt_title.setText("News List");
    }
}

Step 4: Implementation of the List 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);
        // Get the Activity's control
        TextView txt_title = (TextView) getActivity().findViewById(R.id.txt_title);
        txt_title.setText(datas.get(position).getNew_content());
        // Add Fragment replacement animation
        fTransaction.setCustomAnimations(R.anim.fragment_slide_left_enter, R.anim.fragment_slide_left_exit);
        fTransaction.replace(R.id.fl_content, ncFragment);
        // Call addToBackStack to add the Fragment to the stack
        fTransaction.addToBackStack(null);
        fTransaction.commit();
    }
}

Step 5: Implementation of the Content 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 to get the passed Bundle object
        txt_content.setText(getArguments().getString("content"));
        return view;
    }

}

The code is quite simple, so I won't explain it slowly~


3. Code Download

FragmentDemo5.zip : Download FragmentDemo5.zip


Summary of This Section:

>

Due to time constraints, there is no detailed explanation, and the example code is also very simple, which is convenient for beginners to understand! If you want to use it in a real project, you still need to make some modifications! Well, that's it for this section, thank you~

-1.0 Android Basic Tutorial

-1.0.1 Latest Android Basic Tutorial Catalog for 2015

-1.1 Background and System Architecture Analysis

-[1.2 Development Environment Setup](android-tutorial

❮ Android Tutorial Smsmanager Fastjson Intro ❯