Android Studio implements a simple shopping mall interface

project directory

1. Project Overview

With the development of the Internet, the popularization of electronic products such as mobile phones and the rise of e-commerce, people are more and more inclined to shop online without leaving home. Online shopping has become a trend and has occupied a large part of our daily consumption patterns. Most of the things that you can see in life can be bought on shopping platforms.
So how do these shopping platforms display these product lists? How is this information added when we go to browse the product list? With these questions, this project will take you to learn the use of ListView.
The project structure is also very simple, as this is the simplest instance of the application list, with only one Activity file and two layout files.

2. Development environment

3. Detailed design

1. Building a product list

First build the layout file of the product list, the outermost layer is LinearLayout (linear layout), and the orientation (direction) is vertical (vertical), so that the controls in the interface are arranged vertically from top to bottom.

Next, place a TextView control, the width is set to math_parent, that is, the parent container is filled with the same width as the parent container; the height is set to 45dp, the text content text is “shopping mall”, the font size textSize is set to 18sp, and the font color textColor is set to It is white, the background is set to orange, and the gravity (alignment of controls within the layout) is set to center (horizontal center).

Finally, place a ListView control, that is, a list, the width fills the screen, and the height is adaptive. The preview effect is as follows:

The code of activity_main is as follows:

<?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">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:textSize="18sp"
        android:textColor="#FFFFFF"
        android:background="#FF8F03"
        android:gravity="center"/>
    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

2. The construction of commodity items

A ListView must have an item, because a list alone is not enough, and content must be added to the list, and an item is the content displayed in each line in the list. The two complement each other and form a list together.

The construction of the product entry interface only needs to build the item in the first line. The format of other items is the same. You only need to define an array in the main file MainActivity, write the content of the product, and then automatically generate it. So let’s build the item on the first line first.

The outermost layout is RelativeLayout (relative layout), an ImageView control is placed at the top to display the picture of the product, the width and height are set by themselves, and the position is selected to be centered vertically.

Next, a sub-layout RelativeLayout is placed, and the android:layout_toRightOf=”@+id/iv” statement is used to place the sub-layout on the right side of the image just now, and the content is still vertically centered.

In this sub-layout, a TextView control is placed first to display the product name. The text id is set to title, the width and height are set to be adjusted according to the content size, the text content is “table”, the text size is 20sp, and the text color is black.

Another TextView is placed, which is mainly used to display the price. The id is set to tv_price, the width and height are adaptive, and the text content is “price”. Use the android:layout_below=”@+id/title” statement to place it below the TextView of the product name.

Finally, a TextView is placed, which is mainly used to display the number of the price. The specific attribute settings are the same as above, use the android:layout_toRightOf=”@+id/tv_price” statement to place it on the right of the TextView of the price, and set the top margin to 10dp.

Don’t wonder why it is displayed like this, you can treat this whole interface as just one row in the list.

The interface preview effect is as follows:
The list_item code is as follows:

<?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"
    android:padding="10dp">
    <ImageView
        android:id="@+id/iv"
        android:layout_width="150dp"
        android:layout_height="120dp"
        android:layout_centerVertical="true"/>
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_toRightOf="@+id/iv"
        android:layout_centerVertical="true">
        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20sp"
            android:textColor="#000000"/>
        <TextView
            android:id="@+id/tv_price"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20sp"
            android:layout_marginTop="10dp"
            android:layout_below="@+id/title"
            android:textColor="#FF8F03"/>
        <TextView
            android:id="@+id/price"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="1000"
            android:textSize="20sp"
            android:layout_below="@+id/title"
            android:layout_toRightOf="@+id/tv_price"
            android:textColor="#FF8F03"
            android:layout_marginTop="10dp"/>
    </RelativeLayout>
</RelativeLayout>

3, the construction of the data adapter

The main content of LIstView is actually the adapter, and the adapter is very simple. Once you learn it, let’s learn the basics of BaseAdapter first.

3.1. Common data adapters (Adapter)

3.2, the method of BaseAdapter

3.3. Define the data adapter

After building the list, it’s time to define the data adapter in MainActivity to convert the data into a view that we can see.

First, MyBaseAdapter is defined to inherit from BaseAdapter, including four methods:
(1) The getCount method obtains the total number of items and returns the object represented by the ListView Item entry;
(2) The getItem method, the parameter is the subscript of the item, and returns the data object of the item;
(3) The getItemId method, the parameter is the subscript of the item, and the id of the item is returned;
(4) The View getView method is to obtain the Item view corresponding to the corresponding position. position is the position of the current Item, convertView is used to reuse the old view, and parent is used to load the XML layout.

Define a ViewHolder class and declare three member variables. Next, bind the product name title, price price and amount iv to the corresponding control id. If convertView is null, the control will be found and the view will be loaded. If it is not empty, the product information will be displayed directly. The generic template code for the adapter MyBaseAdapter is as follows:

class MyBaseAdapter extends BaseAdapter{

        @Override 
        public  int  getCount () {        //Get the total number of items 
            return titles.length;     //Return the object represented by the ListView Item entry
        }

        @Override 
        public Object getItem ( int position) {
             return titles[position]; //Return the data object of item
        }
        @Override 
        public  long  getItemId ( int position) {
             return position;          //return the id of the item
        }
        @Override 
        public View getView ( int position, View convertView, ViewGroup parent) { //Get the View view in the item
           ViewHolder holder;
           if(convertView==null){
               convertView=View.inflate(MainActivity.this,R.layout.list_item, null);
               holder=new ViewHolder();
               holder.title=convertView.findViewById(R.id.title);
               holder.price=convertView.findViewById(R.id.price);
               holder.iv=convertView.findViewById(R.id.iv);
               convertView.setTag(holder);
           }else{
               holder=(ViewHolder)convertView.getTag();
           }
           holder.title.setText(titles[position]);
           holder.price.setText(prices[position]);
           holder.iv.setImageResource(icons[position]);
           return convertView;
        }
    }

This is the code for ViewHolder, which is actually the controls that each entry needs to display.

class ViewHolder{
        TextView title;
        TextView price;
        ImageView iv;
    }

3.4. Optimize the data adapter

The code just now uses the optimized code using the ViewHolder class and multiplexing convertView, which not only reduces time-consuming operations, but also prevents the problem of memory overflow caused by excessive data volume, killing two birds with one stone.

4. Load the adapter

After defining the adapter, it’s not over yet. We define three arrays in the MainActivity class, namely the titles array, which is used to store the name of the product; the prices array, which is used to store the unit price of each product; the icons collection, which is used to store the imported product images in the drawable (stored here is the id of the image in memory, so it’s an int array). Then use the onCreate method to initialize the control, create the mAdapter reference, and listView.setAdapter(mAdapter);load the adapter by loading the code as follows:

public class MainActivity extends AppCompatActivity {

    //Data that needs to be adapted 
    private String[] titles={ "table" , "apple" , "cake" , "thread clothes" , "kiwi" , "scarf" };
     private String[] prices={ "1800 yuan " , "10 yuan/kg" , "300 yuan" , "350 yuan" , "10 yuan/kg" , "280 yuan" };
     //Picture collection 
    private   int [] icons={R.drawable.table,R .drawable.apple, R.drawable.cake,
            R.drawable.wearclothes,R.drawable.kiwifruit,R.drawable.scarf};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Initialize the ListView control
        ListView listView=findViewById(R.id.lv);
        //Create an instance of Adapter 
        MyBaseAdapter mAdapter= new MyBaseAdapter();
         //Load the adapter
        listView.setAdapter(mAdapter);
    }

So far, the detailed design of the project has been introduced. (Code words are not easy, back pain ing)

5. Complete implementation code

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    //Data that needs to be adapted 
    private String[] titles={ "table" , "apple" , "cake" , "thread clothes" , "kiwi" , "scarf" };
     private String[] prices={ "1800 yuan " , "10 yuan/kg" , "300 yuan" , "350 yuan" , "10 yuan/kg" , "280 yuan" };
     //Picture collection 
    private   int [] icons={R.drawable.table,R .drawable.apple, R.drawable.cake,
            R.drawable.wearclothes,R.drawable.kiwifruit,R.drawable.scarf};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Initialize the ListView control
        ListView listView=findViewById(R.id.lv);
        //Create an instance of Adapter 
        MyBaseAdapter mAdapter= new MyBaseAdapter();
         //Set Adapter
        listView.setAdapter(mAdapter);
    }
    class MyBaseAdapter extends BaseAdapter{

        @Override 
        public  int  getCount () {        //Get the total number of items 
            return titles.length;
        }

        @Override 
        public Object getItem ( int position) {
             return titles[position]; //Return the data object of item
        }
        @Override 
        public  long  getItemId ( int position) {
             return position;          //return the id of the item
        }
        @Override 
        public View getView ( int position, View convertView, ViewGroup parent) { //Get the View view in the item
            ViewHolder holder;
           if(convertView==null){
               convertView=View.inflate(MainActivity.this,R.layout.list_item, null);
               holder=new ViewHolder();
               holder.title=convertView.findViewById(R.id.title);
               holder.price=convertView.findViewById(R.id.price);
               holder.iv=convertView.findViewById(R.id.iv);
               convertView.setTag(holder);
           }else{
               holder=(ViewHolder)convertView.getTag();
           }
           holder.title.setText(titles[position]);
           holder.price.setText(prices[position]);
           holder.iv.setImageResource(icons[position]);
           return convertView;
        }
    }
    class ViewHolder{
        TextView title;
        TextView price;
        ImageView iv;
    }
}

4. Project effect

Open the simulator to run, the product list interface is as shown in the figure, you can drag it up and down.

Note that I only wrote this interface, just to teach you the basic usage of ListView, not a complete shopping mall.

For the complete mall app, please refer to 👉 Android Studio to implement a powerful shopping mall APP 🍝

V. Project Summary

This shopping mall project mainly tests students’ use of ListView and basic controls. I hope everyone can master them proficiently. These knowledge points will be used frequently in Android projects, so I hope everyone can master the use of the above knowledge points to facilitate subsequent development projects.

6. Source code download

Students who need to learn the source code can follow my WeChat public account and reply:shopping mall, you can get the source code, and there are many Android projects waiting for you to learn.

🚀 Here’s what you missed out on

Anything should be tried, because you have no way of knowing what kind of thing or what kind of person will change your life.

​​​​

Leave a Comment

Your email address will not be published. Required fields are marked *