안드로이드 스튜디오 일기 예보 프로그램 실습

실용적인 드릴 날씨 예보 프로그램

(질문이 있으시면 의견을 나누고 함께 소통 할 수 있습니다.)
1. 프로그램을 생성합니다
여기에 사진 설명 삽입
여기에 사진 설명 삽입
. 2. 생성이 완료되면 사용자 인터페이스를 디자인합니다.
activity_main.xml 파일을 편집하십시오. (코드는 다음과 같습니다)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/weather02"
    tools:context="com.example.weather.MainActivity">

    <TextView
        android:id="@+id/tv_city"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignEnd="@+id/tv_weather"
        android:layout_alignParentTop="true"
        android:layout_alignRight="@+id/tv_weather"
        android:layout_marginTop="39dp"
        android:text="上海"
        android:textSize="50sp"/>
    <ImageView
        android:id="@+id/iv_icon"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_alignLeft="@+id/ll_btn"
        android:layout_alignStart="@+id/ll_btn"
        android:layout_below="@+id/tv_city"
        android:layout_marginLeft="44dp"
        android:layout_marginStart="44dp"
        android:layout_marginTop="42dp"
        android:paddingBottom="5dp"
        android:src="@mipmap/ic_launcher" />
    <TextView
        android:id="@+id/tv_weather"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/iv_icon"
        android:layout_below="@+id/iv_icon"
        android:layout_marginRight="15dp"
        android:layout_marginTop="18dp"
        android:gravity="center"
        android:text="多云"
        android:textSize="18sp"/>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/iv_icon"
        android:layout_marginLeft="39dp"
        android:layout_marginStart="39dp"
        android:layout_toEndOf="@+id/iv_icon"
        android:layout_toRightOf="@+id/iv_icon"
        android:gravity="center"
        android:orientation="vertical">
        <TextView
            android:id="@+id/tv_temp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:gravity="center_vertical"
            android:text="- 7 ℃"
            android:textSize="22sp" />
        <TextView
            android:id="@+id/tv_wind"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="风力:3级"
            android:textSize="18sp" />
        <TextView
            android:id="@+id/tv_pm"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="pm"
            android:textSize="18sp"/>
    </LinearLayout>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/cardview_compat_inset_shadow"
        android:text="石周斗专属"/>
    <LinearLayout
        android:id="@+id/ll_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:orientation="horizontal">
        <Button
            android:id="@+id/btn_bj"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="北京"/>
        <Button
            android:id="@+id/btn_sh"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="上海"/>
        <Button
            android:id="@+id/btn_gz"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="广州"/>

    </LinearLayout>
</RelativeLayout>

2. raw 폴더를 생성합니다 (res에서 생성됨).
여기에 사진 설명 삽입
3. raw 폴더가 성공적으로 생성 된 후 그 안에 weather1.xml 파일을 생성합니다 (이 파일에는 날씨에 대한 일부 정보가 포함
됩니다 ). weather.xml 코드는 다음과 같습니다.

<?xml version="1.0" encoding="utf-8"?>
<infos>
    <city id="sh">
        <temp>20`C/30`C</temp>
        <weather>晴转多云</weather>
        <name>上海</name>
        <pm>80</pm>
        <wind>1级</wind>
    </city>
    <city id="bj">
        <temp>26`C/32`C</temp>
        <weather>晴</weather>
        <name>北京</name>
        <pm>98</pm>
        <wind>3级</wind>
    </city>
    <city id="gz">
        <temp>15`C/24`C</temp>
        <weather>多云</weather>
        <name>广州</name>
        <pm>30</pm>
        <wind>5级</wind>
    </city>
</infos>

4. WeatherInfo 클래스를 만들고 (class에 캡슐화 된 weather.xml의 특성을 쉽게 사용하기 위해) WeatherInfo 클래스를 만듭니다. 특정 코드는 다음과 같습니다.

package com.example.weather;

public class WeatherInfo {
    private String id;
    private String temp;
    private String weather;
    private String name;
    private String pm;
    private String wind;
    public String getId(){
        return id;
    }
    public void setId(String id){
        this.id=id;
    }
    public String getTemp(){
        return temp;
    }
    public void setTemp(String temp){
        this.temp=temp;
    }
    public String getWeather(){
       return weather;
    }
    public void setWeather(String weather){
        this.weather=weather;
    }
    public String getName(){
        return name;
    }
    public void setName(String name){
        this.name=name;
    }
    public String getPm(){
        return pm;
    }
    public void setPm(String pm){
        this.pm=pm;
    }
    public String getWind(){
        return wind;
    }
    public void setWind(String wind){
        this.wind=wind;
    }
}

5. WeatherService 도구 클래스를 만듭니다 (코드를 더 쉽게 읽을 수 있도록 한 클래스에 많은 코드를 사용하지 않도록 XML 파일 구문 분석을위한 도구 클래스 WeatherService를 만듭니다).
구체적인 코드는 다음과 같습니다.

package com.example.weather;
import android.util.Xml;
import org.xmlpull.v1.XmlPullParser;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class WeatherService {
    public static List<WeatherInfo> getInfsFromXML (InputStream is) throws Exception{
        XmlPullParser parser= Xml.newPullParser();
        parser.setInput(is,"utf-8");
        List<WeatherInfo> weatherInfos=null;
        WeatherInfo weatherInfo =null;
        int type =parser.getEventType();
        while (type != XmlPullParser.END_DOCUMENT){
            switch (type){
                case XmlPullParser.START_TAG:
                    if ("infos".equals(parser.getName())){
                        weatherInfos= new ArrayList<WeatherInfo>();
                    }else if ("city".equals(parser.getName())){
                        weatherInfo =new WeatherInfo();
                        String idStr =parser.getAttributeValue(0);
                        weatherInfo.setId(idStr);
                    }else if ("temp".equals(parser.getName())){
                        String temp=parser.nextText();
                        weatherInfo.setTemp(temp);
                    }else if ("weather".equals(parser.getName())){
                        String weather =parser.nextText();
                        weatherInfo.setWeather(weather);
                    }else if ("name".equals(parser.getName())){
                        String name =parser.nextText();
                        weatherInfo.setName(name);
                    }else if ("pm".equals(parser.getName())){
                        String pm=parser.nextText();
                        weatherInfo.setPm(pm);
                    }else if ("wind".equals(parser.getName())){
                        String wind =parser.nextText();
                        weatherInfo.setWind(wind);
                    }
                    break;
                case XmlPullParser.END_TAG:
                    if ("city".equals(parser.getName())){
                        weatherInfos.add(weatherInfo);
                        weatherInfo=null;
                    }
                    break;
            }
            type=parser.next();
        }
        return weatherInfos;
    }
}

6. 인터페이스 상호 작용 코드를 작성합니다 (MainActivity.java에서 구문 분석 된 weather1.xml 파일의 데이터가 텍스트 컨트롤에 표시되어야 함). 구체적인 코드는 다음과 같습니다.

package com.example.weather;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private TextView tvCity;
    private TextView tvWeather;
    private TextView tvTemp;
    private TextView tvWind;
    private TextView tvpm;
    private ImageView ivIcon;
    private Map<String,String> map;
    private List<Map<String,String>> list;
    private String temp,weather,name,pm,wind;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        intView();
        try {
            InputStream is=this.getResources().openRawResource(R.raw.weather1);
            List<WeatherInfo> weatherInfos=WeatherService.getInfsFromXML(is);
            list =new ArrayList<Map<String,String>>();
            for (WeatherInfo info:weatherInfos){
                map=new HashMap<String, String>();
                map.put("temp",info.getTemp());
                map.put("weather",info.getWeather());
                map.put("name",info.getName());
                map.put("pm",info.getPm());
                map.put("wind",info.getWind());
                list.add(map);
            }
        } catch (Exception e){
            e.printStackTrace();
            Toast.makeText(this,"解析信息失败",Toast.LENGTH_SHORT).show();
        }
        getMap(1,R.drawable.sun);
    }
    private void intView(){
        tvCity =(TextView) findViewById(R.id.tv_city);
        tvWeather=(TextView) findViewById(R.id.tv_weather);
        tvTemp=(TextView) findViewById(R.id.tv_temp);
        tvWind=(TextView) findViewById(R.id.tv_wind);
        tvpm=(TextView) findViewById(R.id.tv_pm);
        ivIcon =(ImageView) findViewById(R.id.iv_icon);
        findViewById(R.id.btn_sh).setOnClickListener(this);
        findViewById(R.id.btn_gz).setOnClickListener(this);
        findViewById(R.id.btn_bj).setOnClickListener(this);
    }
    public void onClick(View v){
        switch (v.getId()){
            case R.id.btn_sh:
                getMap(0,R.drawable.cloud_sun1);
                break;
            case R.id.btn_bj:
                getMap(1,R.drawable.sun);
                break;
            case R.id.btn_gz:
                getMap(2,R.drawable.clouds);
                break;
        }
    }
    private void getMap(int number,int iconNumber){
        Map<String,String> cityMap=list.get(number);
        temp=cityMap.get("temp");
        weather=cityMap.get("weather");
        name=cityMap.get("name");
        pm=cityMap.get("pm");
        wind=cityMap.get("wind");
        tvCity.setText(name);
        tvWeather.setText(weather);
        tvTemp.setText(""+temp);
        tvWind.setText("风力:"+wind);
        tvpm.setText("pm:"+pm);
        ivIcon.setImageResource(iconNumber);
    }
}

7. 프로그램을 실행합니다 (프로그램을 실행할 때 단일 "북경", "상하이", "광저우"버튼은 다른 도시의 날씨 정보를 표시 할 수 있음). 실행중인 프로그램은 다음과 같습니다.
여기에 사진 설명 삽입
요약 :
다음은 내가 무엇을 실제 전투 훈련을했습니다.
참고 : 우리는 사진을 만들 때 몇 장의 사진을 사용해야하며 그렇게한다면 우리 자신이 인터넷을 검색 할 수 있습니다. 다운로드 한 다음 복사하여 Android 스튜디오에 붙여넣고 직접 복사하여 붙여 넣으십시오. 그러나 그렇게 할 때 일부 사진의 이름에주의를 기울여야합니다. 그렇지 않으면 오류가보고됩니다. 아무것도 이해하지 못하는 경우에는 서로 소통하거나 사적인 메시지 나 댓글을 달 수 있습니다. 메시지를 보면 제 시간에 답장을하겠습니다. 이제 막 시작해서 함께 배웁니다!
여기에 사진 설명 삽입

추천

출처blog.csdn.net/Winda_shi/article/details/115026497