Android development practice - project learning notes

Display weather information [supplement]

in the light of Android development practice - project learning notes (2) , the last part is to improve the code

Add new data
1. Design layout
2. Prepare layout documents
3. Import to parent file
4. Change Java code
① Find control
② Update control content

Step 1:

activity_weather.xml

<?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"
    android:orientation="vertical"
    android:background="@color/colorPrimary"
    tools:context=".WeatherActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize">

        <TextView
            android:id="@+id/title_city"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:textSize="20sp"
            android:textColor="#fff"
            tools:text="Jinan"/>

        <TextView
            android:id="@+id/title_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_centerVertical="true"
            android:textSize="16sp"
            android:textColor="#fff"
            android:layout_marginRight="12dp"
            android:layout_marginEnd="12dp"
            tools:text="15:00" />

    </RelativeLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_margin="16dp">

        <TextView
            android:id="@+id/degree"
            android:textColor="#fff"
            android:textSize="60sp"
            tools:text="20℃"
            android:layout_gravity="end"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/weather_info"
            android:textColor="#fff"
            android:textSize="20sp"
            tools:text="Sunny"
            android:layout_gravity="end"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>

    <LinearLayout
        android:layout_margin="16dp"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#8000">

        <TextView
            android:layout_margin="16dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="prediction"
            android:textColor="#fff"
            android:textSize="20sp"/>

        <LinearLayout
            android:id="@+id/forecast_layout"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        </LinearLayout>

    </LinearLayout>

</LinearLayout>

Among them, the yellow part is a warning, as follows:

Note: hardcoded: hard coded
Solution: under res/values, string Add code to the XML file and click Open Editor, as follows:

If it changes with the system, the following methods can be used to change Chinese and English:


design sketch:

Step 2:

The screen is too small and there are too many contents to display
Note: you can use ScrollView to include all the layouts you want to scroll

Note: ScrollView can only have one child (a layout or control)

<?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"
    android:orientation="vertical"
    android:background="@color/colorPrimary"
    tools:context=".WeatherActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize">

                <TextView
                    android:id="@+id/title_city"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:textSize="20sp"
                    android:textColor="#fff"
                    tools:text="Jinan"/>

                <TextView
                    android:id="@+id/title_time"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_alignParentEnd="true"
                    android:layout_centerVertical="true"
                    android:textSize="16sp"
                    android:textColor="#fff"
                    android:layout_marginRight="12dp"
                    android:layout_marginEnd="12dp"
                    tools:text="15:00" />

            </RelativeLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:layout_margin="16dp">

                <TextView
                    android:id="@+id/degree"
                    android:textColor="#fff"
                    android:textSize="60sp"
                    tools:text="20℃"
                    android:layout_gravity="end"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

                <TextView
                    android:id="@+id/weather_info"
                    android:textColor="#fff"
                    android:textSize="20sp"
                    tools:text="Sunny"
                    android:layout_gravity="end"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

            </LinearLayout>

            <LinearLayout
                android:layout_margin="16dp"
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="#8000">

                <TextView
                    android:layout_margin="16dp"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/forecast"
                    android:textColor="#fff"
                    android:textSize="20sp"/>

                <LinearLayout
                    android:id="@+id/forecast_layout"
                    android:orientation="vertical"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                </LinearLayout>

            </LinearLayout>

        </LinearLayout>

    </ScrollView>

</LinearLayout>

Step 3:

Create API xml
Note: vertical linear layout
1. Upper part: TextView
2. Lower part [bisection]: horizontal linear layout, including two vertical linear layouts [center]
tips: adjust according to the specific situation

<?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="wrap_content"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_margin="16dp"
    android:background="#8000">

    <TextView
        android:text="air quality"
        android:textSize="20sp"
        android:textColor="#fff"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="16dp">

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1">
            
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:orientation="vertical">
                
                <TextView
                    tools:text="20"
                    android:id="@+id/aqi"
                    android:textSize="40sp"
                    android:textColor="#fff"
                    android:layout_gravity="center"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
                
                <TextView
                    android:text="AQI index"
                    android:textColor="#fff"
                    android:textSize="12sp"
                    android:layout_gravity="center"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
            
            </LinearLayout>

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:orientation="vertical">
                
                <TextView
                    tools:text="20"
                    android:id="@+id/pm25"
                    android:textSize="40sp"
                    android:textColor="#fff"
                    android:layout_gravity="center"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
                
                <TextView
                    android:text="PM2.5"
                    android:textColor="#fff"
                    android:textSize="12sp"
                    android:layout_gravity="center"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
            
            </LinearLayout>

        </RelativeLayout>

    </LinearLayout>

</LinearLayout>

design sketch:

  • textColor="#fff" [ffffff] when the value is 3, the transparency is not written by default, and the transparency has no value, so it is opaque; background="#8000"[88000000]
    • A% transparency + RGB hex set color

Step 4:

include introduces other layout files [modular writing]: it is equivalent to copying the imported activity_weather into the file as a whole

activity_weather.xml

WeatherActivity.java


Control found:

Update control content:

Step 5:

Pull down refresh

android.support.v4: extension library, added swiperefreshlayout layout
android.support.v7: textural design
And: Android v7, instead of Android v4

In build Import from gradle with the following code:

implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'

Note: click Sync Now

tips: when pulling down, the layout file is pulled down

activity_weather.xml

<?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"
    android:orientation="vertical"
    android:background="@color/colorPrimary"
    tools:context=".WeatherActivity">

    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        android:id="@+id/refresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize">

                    <TextView
                        android:id="@+id/title_city"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerInParent="true"
                        android:textSize="20sp"
                        android:textColor="#fff"
                        tools:text="Jinan"/>

                    <TextView
                        android:id="@+id/title_time"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentRight="true"
                        android:layout_alignParentEnd="true"
                        android:layout_centerVertical="true"
                        android:textSize="16sp"
                        android:textColor="#fff"
                        android:layout_marginRight="12dp"
                        android:layout_marginEnd="12dp"
                        tools:text="15:00" />

                </RelativeLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:layout_margin="16dp">

                    <TextView
                        android:id="@+id/degree"
                        android:textColor="#fff"
                        android:textSize="60sp"
                        tools:text="20℃"
                        android:layout_gravity="end"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />

                    <TextView
                        android:id="@+id/weather_info"
                        android:textColor="#fff"
                        android:textSize="20sp"
                        tools:text="Sunny"
                        android:layout_gravity="end"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />

                </LinearLayout>

                <LinearLayout
                    android:layout_margin="16dp"
                    android:orientation="vertical"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="#8000">

                    <TextView
                        android:layout_margin="16dp"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/forecast"
                        android:textColor="#fff"
                        android:textSize="20sp"/>

                    <LinearLayout
                        android:id="@+id/forecast_layout"
                        android:orientation="vertical"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content">
                    </LinearLayout>

                </LinearLayout>

                <include layout="@layout/aqi"/>

            </LinearLayout>

        </ScrollView>

    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

</LinearLayout>

design sketch:

WeatherActivity.java


design sketch:

Code part:

WeatherActivity.java

package com.example.jnsyq;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.jnsyq.data.Forecast;
import com.example.jnsyq.data.InTimeWeather;
import com.example.jnsyq.utils.HttpUtils;
import com.google.gson.Gson;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class WeatherActivity extends AppCompatActivity {

    private InTimeWeather inTimeWeather;
    private Forecast forecast;

    //Declare control
    private TextView titleCity;
    private TextView titleTime;
    private TextView degree;
    private TextView weatherInfo;
    private LinearLayout foreLayout;
    private TextView aqi;
    private TextView pm25;

    private String cityid; //private protected public (default: protected)

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what)
            {
                case 0:
                    //Call the update ui method
                    updateUi();
                    break;
                case 1:
                    //Call the 7-day forecast update method
                    updateForecast();
                    break;
                default:
                    break;
            }
        }
    };

    public static void actionStart(Context context, String cityid) {
        Intent intent = new Intent(context, WeatherActivity.class);
        intent.putExtra("cityid", cityid);
        context.startActivity(intent);
    }

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

        //Find control from layout
        titleCity = findViewById(R.id.title_city);
        titleTime = findViewById(R.id.title_time);
        degree = findViewById(R.id.degree);
        weatherInfo = findViewById(R.id.weather_info);
        foreLayout = findViewById(R.id.forecast_layout);
        aqi = findViewById(R.id.aqi);
        pm25 = findViewById(R.id.pm25);

        //Acquisition intention
        Intent intent = getIntent();
        //Get the data from the previous activity
        //Initialize the value of cityid
        cityid = intent.getStringExtra("cityid");

        //Call this method to get data
        getWeatherInfo();
        getForecaseInfo();
    }

    //Data in InTimeWeather
    private void updateUi() {
        //Set corresponding value
        titleCity.setText(inTimeWeather.getCity());
        titleTime.setText(inTimeWeather.getUpdate_time().split(" ")[1]);
        degree.setText(inTimeWeather.getTem() + "℃");
        weatherInfo.setText(inTimeWeather.getWea());
        //Air quality module
        aqi.setText(inTimeWeather.getAir());
        pm25.setText(inTimeWeather.getAir_pm25());
    }

    //Data in Forecast
    private void updateForecast() {
        //Traverse 7-day data
        //forecast.getData().for auto out
        for (Forecast.DataBean dataBean : forecast.getData()) {
            //Create view from layout file
            View view = LayoutInflater.from(this).inflate(R.layout.forecast_item, foreLayout, false);
            //Gets the control of the layout file
            TextView date = view.findViewById(R.id.date);
            TextView wea = view.findViewById(R.id.wea_info);
            TextView hDegree = view.findViewById(R.id.h_degree);
            TextView lDegree = view.findViewById(R.id.l_degree);
            //Set value
            date.setText(dataBean.getWeek());
            wea.setText(dataBean.getWea());
            hDegree.setText(dataBean.getTem1());
            lDegree.setText(dataBean.getTem2());
            //Add layout view
            foreLayout.addView(view);
        }
    }

    /**
     * Create a method to get real-time weather
     */
    private void getWeatherInfo() {
        //Obtain weather information by calling api
        //Obtain weather information directly through ip address
        //cityid: variable passed in by the previous activity
        String url = "http://www.tianqiapi.com/api?version=v6&appid=72458447&appsecret=E2P8xV9n&cityid=" + cityid.replace("CN", "");
        //Get network information
        //Network access requires a new thread to execute without affecting the main thread
        HttpUtils.sendOkhttpRequest(url, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                //Read the returned data
                String data = response.body().string();
                //New gson object
                Gson gson = new Gson();
                //Parse json data and initialize inTimeWeather
                inTimeWeather = gson.fromJson(data, InTimeWeather.class); //json formatting

                //After initializing the weather, send a message to update the ui interface
                Message msg = new Message();
                msg.what = 0;
                handler.sendMessage(msg);
            }
        });
    }

    /**
     * Create a method to obtain seven day weather data
     */
    private void getForecaseInfo() {
         String url = "http://www.tianqiapi.com/api?version=v1&appid=72458447&appsecret=E2P8xV9n&cityid="
                + cityid.replace("CN", "");
         HttpUtils.sendOkhttpRequest(url, new Callback() {
             @Override
             public void onFailure(@NotNull Call call, @NotNull IOException e) {
                 e.printStackTrace();
             }

             @Override
             public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String data = response.body().string();
                Gson gson = new Gson();
                forecast = gson.fromJson(data, Forecast.class);

                 Message msg = new Message();
                 msg.what = 1;
                 handler.sendMessage(msg);
             }
         });
    }

}

design sketch:

Note: it can slide down

Tags: Android Design Pattern

Posted by blackthunder on Mon, 23 May 2022 21:28:03 +0300