Android 简易版天气预报app的现实(4)

来源:互联网 发布:python程序设计答案 编辑:程序博客网 时间:2024/04/29 15:13

在这一讲开始天气显示界面WeatherActivity类的编写~

一、在第一讲的时候展示过天气信息界面的图片,在图片中下边是一个ListView组件,用来显示当天对某个时间段的天气预测。设置一个ListView,需要为其指定一个布局,设定其数据的排列方式。
所以,在layout文件夹下新建一个布局文件,命名为hourly_forecast.xml。因为我获取的数据有时间点、温度、降水概率、风力等四种信息,所以为布局文件指定了四个TextView组件。

<?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" >    <!-- 时间 -->    <TextView        android:id="@+id/clock"        android:layout_width="0dp"        android:layout_height="fill_parent"        android:layout_weight="2"        android:background="#A6A6A6"        android:gravity="center"        android:textSize="20sp"        android:textStyle="bold" />    <LinearLayout        android:layout_width="0dp"        android:layout_height="fill_parent"        android:layout_weight="5"        android:background="#A6A6A6"        android:orientation="vertical" >        <!-- 温度   下雨概率 -->        <LinearLayout            android:layout_width="fill_parent"            android:layout_height="0dp"            android:layout_weight="1"            android:background="#A6A6A6"            android:gravity="center"            android:orientation="horizontal" >            <!-- 温度 -->            <TextView                android:id="@+id/tmp"                android:layout_width="0dp"                android:layout_height="fill_parent"                android:layout_weight="1"                android:background="#A6A6A6"                android:gravity="center" />            <!-- 下雨概率 -->            <TextView                android:id="@+id/pop"                android:layout_width="0dp"                android:layout_height="fill_parent"                android:layout_weight="1"                android:background="#A6A6A6"                android:gravity="center" />        </LinearLayout>        <!-- 风力 -->        <TextView            android:id="@+id/wind"            android:layout_width="fill_parent"            android:layout_height="0dp"            android:layout_weight="1"            android:background="#A6A6A6"            android:gravity="center" />    </LinearLayout></LinearLayout>

二、因为在某个时间点要获取的天气预报的信息类型是固定不变的,所以可以为之抽象为一个HourlyWeather类。新建一个com.czy.weather.Adapter包,在包下新建一个HourlyWeather类。

package com.czy.weather.Adapter;public class HourlyWeather {    // 预测时间    private String clock;    // 温度    private String tmp;    // 降水概率    private String pop;    // 风力    private String wind;    public HourlyWeather(String clock, String tmp, String pop, String wind) {        this.clock = clock;        this.tmp = tmp;        this.pop = pop;        this.wind = wind;    }    public String getClock() {        return clock;    }    public String getTmp() {        return tmp;    }    public String getPop() {        return pop;    }    public String getWind() {        return wind;    }}

再新建一个 WeatherAdapter类继承ArrayAdapter,代码如下:

package com.czy.weather.Adapter;import java.util.List;import android.annotation.SuppressLint;import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.TextView;import com.czy.weather.R;public class WeatherAdapter extends ArrayAdapter<HourlyWeather> {    private int resourceId;    public WeatherAdapter(Context context, int textViewResourceId,            List<HourlyWeather> objects) {        super(context, textViewResourceId, objects);        this.resourceId = textViewResourceId;    }    @SuppressLint("ViewHolder")    public View getView(int position, View convertView, ViewGroup parent) {        HourlyWeather wea = getItem(position);        View view = LayoutInflater.from(getContext()).inflate(resourceId, null);        TextView clock_text = (TextView) view.findViewById(R.id.clock);        TextView tmp_text = (TextView) view.findViewById(R.id.tmp);        TextView pop_text = (TextView) view.findViewById(R.id.pop);        TextView wind_text = (TextView) view.findViewById(R.id.wind);        clock_text.setText(wea.getClock());        tmp_text.setText(wea.getTmp());        pop_text.setText(wea.getPop());        wind_text.setText(wea.getWind());        return view;    }}

三、在com.czy.weather.Activity包下再新建一个WeatherActivity继承Activity类。在layout文件夹下再新建一个weather_layout.xml文件,为WeatherActivity类设计布局文件。

<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"    android:orientation="vertical" >    <RelativeLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:background="#abc" >        <!-- 切换城市 -->        <Button            android:id="@+id/switch_city"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_alignParentLeft="true"            android:layout_centerVertical="true"            android:text="切换城市" />        <!-- 重新查询 -->        <Button            android:id="@+id/refresh_weather"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_alignParentRight="true"            android:text="更新数据" />    </RelativeLayout>    <!-- 天气简要信息 -->    <LinearLayout        android:id="@+id/weather_info_layout"        android:layout_width="match_parent"        android:layout_height="0dp"        android:layout_weight="3"        android:orientation="horizontal" >        <!-- 信息 -->        <LinearLayout            android:layout_width="0dp"            android:layout_height="fill_parent"            android:layout_weight="2"            android:orientation="vertical" >            <!-- 城市 -->            <TextView                android:id="@+id/city_name"                android:layout_width="wrap_content"                android:layout_height="0dp"                android:layout_gravity="center"                android:layout_weight="1"                android:gravity="center"                android:textSize="30sp"                android:textStyle="bold" />            <!-- 天气 -->            <TextView                android:id="@+id/weather_desp"                android:layout_width="wrap_content"                android:layout_height="0dp"                android:layout_gravity="center"                android:layout_weight="1"                android:gravity="center" />            <!-- 温度 -->            <TextView                android:id="@+id/weather_tmp"                android:layout_width="wrap_content"                android:layout_height="0dp"                android:layout_gravity="center"                android:layout_weight="1"                android:gravity="center" />        </LinearLayout>        <!-- 各种信息 -->        <LinearLayout            android:layout_width="0dp"            android:layout_height="fill_parent"            android:layout_weight="3"            android:orientation="vertical" >            <!-- 日出日落 -->            <LinearLayout                android:layout_width="fill_parent"                android:layout_height="0dp"                android:layout_weight="1"                android:orientation="horizontal" >                <TextView                    android:id="@+id/sr"                    android:layout_width="0dp"                    android:layout_height="wrap_content"                    android:layout_gravity="center"                    android:layout_weight="1"                    android:gravity="center" />                <TextView                    android:id="@+id/ss"                    android:layout_width="0dp"                    android:layout_height="wrap_content"                    android:layout_gravity="center"                    android:layout_weight="1"                    android:gravity="center" />            </LinearLayout>            <!-- 降水概率  风力 -->            <LinearLayout                android:layout_width="fill_parent"                android:layout_height="0dp"                android:layout_weight="1"                android:orientation="horizontal" >                <TextView                    android:id="@+id/windText"                    android:layout_width="0dp"                    android:layout_height="wrap_content"                    android:layout_gravity="center"                    android:layout_weight="1"                    android:gravity="center" />                <TextView                    android:id="@+id/pop"                    android:layout_width="0dp"                    android:layout_height="wrap_content"                    android:layout_gravity="center"                    android:layout_weight="1"                    android:gravity="center" />            </LinearLayout>            <!-- 发布时间 -->            <TextView                android:id="@+id/publish_time_text"                android:layout_width="wrap_content"                android:layout_height="0dp"                android:layout_gravity="center"                android:layout_weight="1"                android:gravity="center" />        </LinearLayout>    </LinearLayout>    <ListView        android:id="@+id/hourly_forecast"        android:layout_width="fill_parent"        android:layout_height="0dp"        android:layout_weight="6"        android:background="#4177C5" >    </ListView></LinearLayout>

四、WeatherActivity类的代码如下所示:

package com.czy.weather.Activity;import java.util.ArrayList;import java.util.List;import android.app.Activity;import android.content.Intent;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;import android.os.Bundle;import android.preference.PreferenceManager;import android.text.TextUtils;import android.view.View;import android.view.View.OnClickListener;import android.view.Window;import android.widget.Button;import android.widget.LinearLayout;import android.widget.ListView;import android.widget.TextView;import android.widget.Toast;import com.czy.weather.R;import com.czy.weather.Adapter.HourlyWeather;import com.czy.weather.Adapter.WeatherAdapter;import com.czy.weather.Util.HttpCallbackListener;import com.czy.weather.Util.HttpUtil;import com.czy.weather.Util.Utility;public class WeatherActivity extends Activity implements OnClickListener {    private LinearLayout weatherInfoLayout;    // 城市切换按钮    private Button switch_city_button;    // 更新按钮    private Button refresh_weather_button;    // 城市名    private TextView city_name_text;    // 天气描叙    private TextView weather_desp_text;    // 温度    private TextView weather_tmp_text;    // 日出时间    private TextView sr_text;    // 日落时间    private TextView ss_text;    // 风力    private TextView wind_text;    // 降水概率    private TextView pop_text;    // 发布时间    private TextView publish_time_text;    // 今日天气预测列表    private ListView listview;    public static List<HourlyWeather> weatherList = new ArrayList<HourlyWeather>();    private SharedPreferences prefs;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        requestWindowFeature(Window.FEATURE_NO_TITLE);        setContentView(R.layout.weather_layout);        switch_city_button = (Button) findViewById(R.id.switch_city);        refresh_weather_button = (Button) findViewById(R.id.refresh_weather);        weatherInfoLayout = (LinearLayout) findViewById(R.id.weather_info_layout);        city_name_text = (TextView) findViewById(R.id.city_name);        weather_desp_text = (TextView) findViewById(R.id.weather_desp);        weather_tmp_text = (TextView) findViewById(R.id.weather_tmp);        sr_text = (TextView) findViewById(R.id.sr);        ss_text = (TextView) findViewById(R.id.ss);        wind_text = (TextView) findViewById(R.id.windText);        pop_text = (TextView) findViewById(R.id.pop);        publish_time_text = (TextView) findViewById(R.id.publish_time_text);        listview = (ListView) findViewById(R.id.hourly_forecast);        prefs = PreferenceManager.getDefaultSharedPreferences(this);        String county_name = getIntent().getStringExtra("county_name");        // 当county_name不为空        if (!TextUtils.isEmpty(county_name)) {            Editor editor = prefs.edit();            editor.putString("county_name", county_name);            editor.commit();            publish_time_text.setText("同步中……");            weatherInfoLayout.setVisibility(View.INVISIBLE);            city_name_text.setVisibility(View.INVISIBLE);            queryFromServer(county_name);        } else {            county_name = prefs.getString("city_name", "未知");            publish_time_text.setText("同步中……");            weatherInfoLayout.setVisibility(View.INVISIBLE);            city_name_text.setVisibility(View.INVISIBLE);            queryFromServer(county_name);        }        switch_city_button.setOnClickListener(this);        refresh_weather_button.setOnClickListener(this);    }    @Override    public void onClick(View view) {        switch (view.getId()) {        case R.id.switch_city:            Intent intent = new Intent(this, ChooseAreaActivity.class);            intent.putExtra("from_weather_activity", true);            startActivity(intent);            finish();            break;        case R.id.refresh_weather:            publish_time_text.setText("同步中……");            String county_nmae = prefs.getString("county_name", "");            if (!TextUtils.isEmpty(county_nmae)) {                queryFromServer(county_nmae);                Toast.makeText(WeatherActivity.this, "更新成功", Toast.LENGTH_SHORT)                        .show();            }            break;        default:            break;        }    }    private void queryFromServer(final String county_name) {        try {            String hh = "http://apis.baidu.com/heweather/weather/free?city=";            String hhh = new String(county_name.getBytes("UTF-8"), "iso-8859-1");            HttpUtil.sendHttpRequest(hh + hhh, new HttpCallbackListener() {                @Override                public void onFinish(String response) {                    Utility.handleWeatherResponse(WeatherActivity.this,                            response);                    runOnUiThread(new Runnable() {                        @Override                        public void run() {                            showWeather();                        }                    });                }                @Override                public void onError(Exception e) {                    runOnUiThread(new Runnable() {                        @Override                        public void run() {                            publish_time_text.setText("同步失败");                        }                    });                }            });        } catch (Exception e) {            e.printStackTrace();        }    }    private void showWeather() {        city_name_text.setText(prefs.getString("city_name", "未知"));        weather_desp_text.setText(prefs.getString("weather", "未知"));        weather_tmp_text.setText("温度:" + prefs.getString("minTmp", "0") + " ~ "                + prefs.getString("maxTmp", "0"));        sr_text.setText("日出:" + prefs.getString("sr", ""));        ss_text.setText("日落: " + prefs.getString("ss", ""));        wind_text.setText("风力: " + prefs.getString("windText", ""));        pop_text.setText("降水概率: " + prefs.getString("pop", ""));        publish_time_text.setText(prefs.getString("publish_time", "0"));        WeatherAdapter adapter = new WeatherAdapter(this,                R.layout.hourly_forecast, weatherList);        listview.setAdapter(adapter);        city_name_text.setVisibility(View.VISIBLE);        weatherInfoLayout.setVisibility(View.VISIBLE);        listview.setVisibility(View.VISIBLE);    }}

WeatherActivity类较为简单,都是以前边介绍的各个工具类为基础,获取数据并显示。
最后,在AndroidManifest.xml文件中设定主Activity为ChooseAreaActivity,并声明WeatherActivity类。然后,还要为程序申请联网权限:

<uses-permission android:name="android.permission.INTERNET" />

这样,一个简单版的天气预报app就完成了~

项目代码的下载地址在这里:天气预报项目代码

0 0
原创粉丝点击