The use of Fragment in Android case -- Sichuan cuisine menu

The use of Fragment in Android case -- Sichuan cuisine menu

This case will demonstrate how to display two fragments in one Activity (one Fragment is used to display the list of Sichuan cuisine and one Fragment is used to display the practice of Sichuan cuisine), and realize the communication function between Activity and Fragment

1. Preparation

Import two required pictures into the mipmap folder, and click activity in the res/layout folder_ main. Two fragment s are added to the XML file to display the menu list and recipe information respectively

2. Create two Fragment layout files

Create layout file fragments in res/layout folder respectively_ menu. XML and fragment_content.xml to display the layout file fragment of Sichuan cuisine list_ menu. A ListView control is placed in the XML to display the list and display the layout file fragment of the practice of dishes_ content. A TextView is placed in the XML file to display the dish practice information

fragment_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ListView
        android:id="@+id/menulist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

fragment_content.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:textSize="18sp"
        android:centerVertical="true"
        android:layout_alignParentLeft="true"/>
</LinearLayout>

3. Create Sichuan cuisine list Item interface

Because the ListView control is used in the interface displaying the list of Sichuan dishes, an Item interface needs to be created for the list

Create a layout file Item of the Item interface in the res/layout folder_ list. XML, in which an ImageView control is placed to display the picture of the dish and a TextView control is used to display the name of the dish

item_list.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <ImageView
        android:layout_width="100dp"
        android:layout_height="40dp"
        android:id="@+id/food_icon"
        android:layout_centerInParent="true"
        android:layout_margin="10dp"/>
    <TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/food_name"
    android:layout_below="@+id/food_icon"
    android:gravity="center"/>
</RelativeLayout>

4. Create ContentFragment

Create a ContentFragment class that inherits from Fragment, get the interface control in this class, and display the dishes on the control

ContentFragment.java

package com.example.test;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class ContentFragment extends Fragment{
    private View view;
    private TextView mContent;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }
    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
        //Parse the layout file
        view = inflater.inflate(R.layout.fragment_content,container,false);
        if(view!=null){
            initView();
        }
        //Gets the text set in the Activity
        setText(((MainActivity)getActivity()).getSettingText()[0];
        return view;
    }
    public void initView(){
        mContent = (TextView)view.findViewById(R.id.content);
    }
    public void setText(String text){
        mContent.setText(text);
    }
}

The code in line 29 displays the obtained dish practice data information set in the Activity to the interface control through the setText() method

5. Create MenuFragment

MenuFragment.java

package com.example.test;

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class MenuFragment extends Fragment{
    private View view;
    private int[] settingicon;
    private String[] foodNames;
    private String[] settingText;
    private ListView mListView;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        //Load layout file
        view = inflater.inflate(R.layout.fragment_menu,container,false);
        //Get Activity instance object
        MainActivity activity = (MainActivity)getActivity();
        settingicon = activity.getIcons();//Get picture data in Activity
        foodNames = activity.getNames();//Get the name of Sichuan cuisine defined in Activity
        //Get the dish practice data set in the Activity
        settingText = activity.getSettingText();
        if (view!=null){
            initView();
        }
        //Set Item listening for ListView, click Item in the list on the left, and the corresponding dish practice information will be displayed on the right
        mListView.setOnClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Get another Fragment instance through the Activity instance
                ContentFragment listFragment = (ContentFragment)((MainActivity)getActivity()).getFragmentManager().findFragmentById(R.id.foodcontent);
                //Click the recipe information corresponding to Item
                listFragment.setText(settingText[position]);
            }
        });
        return view;
    }
    //Method of initializing control
    private void initView(){
        mListView = (ListView)view.findViewById(R.id.menulist);
        if(settingicon!=null){
            mListView.setAdapter(new MyAdaptter());
        }
    }
    class MyAdapter extends BaseAdapter{
        @Override
        public int getCount() {
            return settingicon.length;
        }
        @Override
        public Object getItem(int position) {
            return settingicon[position];
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = View.inflate(getActivity(),R.layout.item_list,null);
            ImageView mNameTV = (ImageView)convertView.findViewById(R.id.food_icon);
            mNameTV.setBackgroundResource(settingicon[position]);
            TextView mFoodName = (TextView)convertView.findViewById(R.id.food_name);
            mFoodName.setText(foodNames[position]);
            return convertView;
        }
    }
}

The code in line 38 adds a click event listener to the Item in the list through the setOnItemClickListener() method, and overrides the onItemClick() method in the listener

In the onItemClick() method, first get the instance object of Activity through getActivity() method, then get the instance object of FragmentManager through getFragmentManager() method of object, finally get the content fragment object listFragment through findFragmentById() method, and call setText() method to set the dish practice information corresponding to the clicked Item

Key statements:

//Get another Fragment instance through the Activity instance
ContentFragment listFragment = (ContentFragment)((MainActivity)getActivity()).getFragmentManager().findFragmentById(R.id.foodcontent);

6. Write the code in MainActivity

Add MenuFragment and ContentFragment to MainActivity interface in MainActivity

package com.example.test;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;

public class MainActivity extends Activity {
    private FragmentTransaction beginTransaction;
    //Dish practice data
    private String[] settingText = {""+"1.Mix egg white and starch seasoning into a paste and apply it to the meat\n"+"2...\n"+"3...\n"+"4...\n","1.Diced tofu, chopped chives, ginger and garlic, set aside"+"2...\n"+"3...\n"+"4...\n"};
   //Set dish picture data
    private int[] settingicons = {R.drawable.chicken,R.drawable.tofu};
   private String[] foodNames = {"Boiled meat","Mapo Tofu"};
    //Method for obtaining dish picture data
    public int[] geticons(){
        return settingicons;
    }
    public String [] getFoodNames(){
        return foodNames;
    }
    //Gets or sets the method of text
    public String[] getSettingText(){
        return settingText;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Create Fragment instance object
        ContentFragment contentFragment = new ContentFragment();
        MenuFragment menuFragment = new MenuFragment();
        beginTransaction = getFragmentManager().beginTransaction();
        //Get things add Fragment
        beginTransaction.replace(R.id.foodcontent,contentFragment);
        beginTransaction.replace(R.id.menu,menuFragment);
        beginTransaction.commit();
    }
}

7. Start up test

If the article is helpful to you, remember to support it with one key and three links~

Keywords: Java Android Android Studio xml Back-end

Added by flumpy on Mon, 31 Jan 2022 01:07:48 +0200