Android Studio beginner example: Fragment learning - imitation Meituan takeaway interface

The theme of this course is Fragment. The example of the course imitates the Meituan takeaway interface, which is different from the Fragment case in the bottom navigation bar. This interface is divided into left switching and top switching. This article first releases the code and effects, and subsequent explanations will be added later. First look at the effect:

The first is the layout file code: Activity layout: activity_main.xml:

First, use the LinearLayout layout for the parent layout, and set the layout direction to vertical layout through the code: android:orientation="vertical". The interface is divided into the top navigation bar, the left menu bar, and the right menu bar, which are divided into three major sub-layouts

RelativeLayout and LinearLayout are used respectively (the left and right layouts are placed in a LinearLayout, and the layout direction can be set to horizontal)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">


    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginBottom="4dp"
        android:gravity="center_vertical">

        <TextView
            android:id="@+id/tv_order"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="25dp"
            android:layout_marginTop="4dp"
            android:textSize="16sp"

            android:text="点菜"
           />
        <TextView
            android:id="@+id/tv_discuss"
            android:layout_toRightOf="@id/tv_order"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="25dp"
            android:layout_marginTop="4dp"
            android:textSize="16sp"
            android:text="评价"
            />
        <TextView
            android:id="@+id/tv_business"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="25dp"
            android:layout_marginTop="4dp"
            android:layout_toRightOf="@id/tv_discuss"
            android:textSize="16sp"
            android:text="商家"
             />

        <TextView

            android:layout_width="70dp"
            android:layout_height="30dp"
            android:layout_marginLeft="25dp"
            android:layout_marginTop="4dp"
            android:textSize="12sp"
            android:layout_alignParentRight="true"
            android:layout_marginRight="15dp"
            android:background="@drawable/friend_list"
            android:gravity="center"
            android:textColor="#ef842c"
            android:text="好友拼单"
             />
    </RelativeLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        >
        <fragment
            android:id="@+id/left"
            android:name="com.example.student.LeftFragment"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"

            tools:layout="@layout/fragment_left"/>
        <fragment
            android:id="@+id/right"
            android:name="com.example.student.RightFragment"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="3"
            tools:layout="@layout/fragment_right"
            />

    </LinearLayout>
</LinearLayout>

 Two Fragment layout codes

fragment_left.xml:

The recommendation on the left navigation bar and the must-buy when entering the store, in the final effect, you need to click these two TextViews to change the data in the right navigation bar

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context=".LeftFragment"
    android:orientation="vertical">
    <TextView
        android:id="@+id/tv_recommend"
        android:layout_width="100dp"
        android:layout_height="40dp"
        android:gravity="center"
        android:textSize="12sp"
        android:text="推荐" />
    <TextView
        android:id="@+id/tv_must_buy"
        android:layout_width="100dp"
        android:layout_height="40dp"
        android:gravity="center"
        android:textSize="12sp"
        android:text="进店必买"/>
</LinearLayout>

 fragment_right.xml:

Listview is used to display list data

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".RightFragment"
    android:orientation="vertical">
    <ListView
        android:id="@+id/lv_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:divider="@null"
        />
</FrameLayout>

And the item layout of LIstview in fragment_right:

list_item.xml

The item contains an ImageView for displaying food picture information, and three TextViews for displaying food titles, food ratings, and food prices. Similarly, the sub-layout adopts a LinearLayout layout, and sets the layout direction to be vertical, so that the three TextViews are placed vertically put

<?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="horizontal"
    android:padding="5dp">
    <ImageView
        android:id="@+id/iv_img"
        android:layout_width="70dp"
        android:layout_height="70dp"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:orientation="vertical"
        >
        <TextView
            android:textSize="14sp"
            android:padding="2dp"
            android:id="@+id/tv_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#868788"
            android:id="@+id/tv_sale"

            android:textSize="12sp"/>
        <TextView
            android:id="@+id/tv_price"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="2dp"

            android:textSize="12sp"/>
    </LinearLayout>
</LinearLayout>

Next is the Java logic code:

MainActivity.java:

The onCreate() function is executed during the creation of the Activity life cycle, in which the setData, init, and clickEvent methods are executed, which are three custom methods.
setData method: assign values ​​to the data and put them all in the corresponding data set, that is, add two sections of ListVIew to the actual data at that time;
init method: Assign values ​​to the fragment interface controls on the left side of the main page (bind controls), and obtain FragmentManager, the object that manages Fragments;
clickEvent method: Generate a click event on the left navigation bar, and click to realize the color change of the control, which can increase the flexibility.
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentTransaction;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity52 extends AppCompatActivity {
    private FragmentManager fragmentManager;
    private FragmentTransaction fragmentTransaction;
    private Fragment leftFragment;
    private RightFragment rightFragment;
    private TextView tv_recommed,tv_must_buy;
    private TextView btn;
    private String[]names1={"爆款*肥牛鱼豆腐骨肉相连三荤五素一份米饭","豪华双人套餐","【热销】双人套餐(含两份米饭)"};
    private String[]sales1={"月售520 好评度80%","月售520 好评度80%","月售520 好评度80%"};
    private String[]prices1={"$23","$41","$32"};
    private int []imgs1={R.drawable.recom_one,R.drawable.recom_two,R.drawable.recom_three};


    private String[]names2={"素菜主义一人套餐","两人经典套套餐","三人经典套餐"};
    private String[]sales2={"月售520 好评度80%","月售520 好评度80%","月售520 好评度80%"};
    private String[]prices2={"$23","$41","$32"};
    private int []imgs2={R.drawable.must_buy_one,R.drawable.must_buy_two,R.drawable.must_buy_three};

    private Map<String, List<FoodsBean>>map;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main52);

        setData();
        init();
        clickEvent();
    }
    private void init(){//给主页面左侧的fragment界面控件赋值

        fragmentManager = getFragmentManager();

        leftFragment=fragmentManager.findFragmentById(R.id.left);
        tv_recommed=findViewById(R.id.tv_recommend);

        tv_must_buy=findViewById(R.id.tv_must_buy);

    }
    private void setData(){//给数据赋值将其全部放在对应的数据集里
        map=new HashMap<>();
        List<FoodsBean>list1=new  ArrayList<>();
        List<FoodsBean>list2=new ArrayList<>();
        for(int i=0;i<names1.length;i++){
            FoodsBean bean=new FoodsBean();
            bean.setName(names1[i]);
            bean.setPrice(prices1[i]);
            bean.setImg(imgs1[i]);
            bean.setSales(sales1[i]);
            list1.add(bean);
        }
        map.put("1",list1);
        for(int i=0;i<names2.length;i++){
            FoodsBean bean=new FoodsBean();
            bean.setName(names2[i]);
            bean.setPrice(prices2[i]);
            bean.setImg(imgs2[i]);
            bean.setSales(sales2[i]);
            list2.add(bean);
        }
        map.put("2",list2);

    }
    private void clickEvent(){//点击推荐还在必须控件变化颜色,可以增加可适度
        tv_recommed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switchData (map.get("1"));
                tv_recommed.setBackgroundColor(Color.WHITE);
            }
        });
        tv_must_buy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switchData (map.get("2"));
                tv_must_buy.setBackgroundColor(Color.WHITE);
            }
        });
        switchData (map.get("1"));
    }
    public void switchData(List<FoodsBean> list){

        rightFragment=new RightFragment().getInstance(list);//实例fragment

        fragmentManager=getFragmentManager();//获取FragmentManager

        fragmentTransaction=getSupportFragmentManager().beginTransaction();//开启事务

        fragmentTransaction.replace(R.id.right,rightFragment);//添加一个Fragment


        fragmentTransaction.commit();//提交事务

    }

}

Food entity class FoodsBean:

I won’t talk too much about the entity class, after all, it is object-oriented

import java.io.Serializable;

public class FoodsBean implements Serializable {
    private static final long serialVersionUID=1L;
    private String name;
    private String sales;
    private String price;
    private int img;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSales() {
        return sales;
    }

    public void setSales(String sales) {
        this.sales = sales;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public int getImg() {
        return img;
    }

    public void setImg(int img) {
        this.img = img;
    }
}

 The Java code of LeftFragment in Fragment:

LeftFragment:

In fact, only rewriting the onCreateView method can also be done. That is to bind the view

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import org.jetbrains.annotations.NotNull;

public class LeftFragment extends Fragment {
    @Override
    public void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @org.jetbrains.annotations.Nullable
    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_left,container,false);
        return view;
    }

    @Override
    public void onPause() {
        super.onPause();
    }
}

Another RightFragment:

RightFragment:

Because it is more complicated than LeftFragment to realize data switching and Listview data display

Also rewrite the method. And wrote a construction method for setting data, setArguments is used for communication between Activity and Fragment, because of some problems in the life cycle of Activity and Fragment, it cannot be passed through simple data

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import org.jetbrains.annotations.NotNull;

import java.io.Serializable;
import java.util.List;

public class RightFragment extends Fragment {
    private ListView lv_list;
    public RightFragment(){

    }
    public  RightFragment getInstance(List<FoodsBean> list){
        RightFragment rightFragment=new RightFragment();
        Bundle bundle=new Bundle();
        bundle.putSerializable("list", (Serializable) list);
        rightFragment.setArguments(bundle);
        return  rightFragment;
    }

    @Override
    public void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @org.jetbrains.annotations.Nullable
    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_right,container,false);
        lv_list=view.findViewById(R.id.lv_list);
        if(getArguments()!=null){
            List<FoodsBean> list= (List<FoodsBean>) getArguments().getSerializable("list");
            RightAdapter adapter=new RightAdapter(getActivity(),list);
            lv_list.setAdapter(adapter);
        }
        return  view;
    }
}

Adapter code for ListView in RightFargment:

RightAdapter:

The role of the adapter is to bind data and views, rewrite the getCount, getItem, getItemId, and getView methods in the adapter, and create an internal class ViewHolder in order to reuse ViewHolder, where list is a list that stores food data, and the type is List <FoodsBean>, getView is to obtain the view of the item and set the data. The rest of the overridden methods can be roughly understood through the name. For example, getCount means the number of items, so just return the length of the list and call the size method

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;


import java.util.List;

public class RightAdapter extends BaseAdapter {
    private Context mContext;
    private List<FoodsBean>list;
    public RightAdapter(Context context , List<FoodsBean>list){
        this.mContext=context;
        this.list=list;
    }
    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder=null;
        if(convertView==null){
            convertView=View.inflate(mContext,R.layout.list_item,null);
            holder= new ViewHolder();
            holder.tv_name=convertView.findViewById(R.id.tv_name);
            holder.tv_sale=convertView.findViewById(R.id.tv_sale);
            holder.tv_price=convertView.findViewById(R.id.tv_price);
            holder.iv_img=convertView.findViewById(R.id.iv_img);
            convertView.setTag(holder);
        }else {
            holder=(ViewHolder) convertView.getTag();
        }
        FoodsBean bean=list.get(position);
        holder.tv_name.setText(bean.getName());
        holder.tv_sale.setText(bean.getSales());
        holder.tv_price.setText(bean.getPrice());
        holder.iv_img.setBackgroundResource(bean.getImg());
        return convertView;
    }
    class ViewHolder{
        TextView tv_name,tv_sale,tv_price;
        ImageView iv_img;
    }
}

A brief summary:

In this experiment, we learned Fragment as the main knowledge, which runs through a relatively important knowledge point of Listview. The interface is divided into top navigation bar, left menu bar, and right menu bar. The switching function of the top navigation bar in the current experiment It has not been realized yet, and it can be added in the future. The menu bar on the left has the effect of switching the content displayed in the menu on the right by clicking. The English word Fragment means fragments. To put it simply, Fragment can actually be understood as a control with its own life cycle, but this control is a bit special. It has its own ability to process input events, has its own life cycle, and must depend on Activity to communicate with each other. and hosting. Using Fragment can simplify the code of the Activity file, which is easier to read, and at the same time, has a better speed of loading.

Guess you like

Origin blog.csdn.net/m0_59558544/article/details/130313931