Repository: HuTianQi/CoolWeather
Branch: master
Commit: 0e0ac4f9d40e
Files: 89
Total size: 141.7 KB
Directory structure:
gitextract_opkz8o5j/
├── .classpath
├── .project
├── .settings/
│ └── org.eclipse.jdt.core.prefs
├── AndroidManifest.xml
├── LICENSE
├── README.md
├── libs/
│ ├── BaiduLBS_Android.jar
│ ├── android-support-v4.jar
│ ├── gson-2.1.jar
│ └── universal-image-loader-1.8.4.jar
├── lint.xml
├── proguard-project.txt
├── project.properties
├── res/
│ ├── drawable/
│ │ ├── citym_normal_bg.xml
│ │ ├── citym_normal_color.xml
│ │ ├── drawerlayout_bt_bg.xml
│ │ ├── drawerlayout_button_bg.xml
│ │ ├── exitapp_text_bg.xml
│ │ ├── homep_search_bg.xml
│ │ ├── homep_titlebt_bg.xml
│ │ ├── homep_titlemenu_bg.xml
│ │ ├── inputcity_edit.xml
│ │ ├── item_citym_normal_bg.xml
│ │ ├── item_citym_normal_color.xml
│ │ ├── item_todayc_bg.xml
│ │ ├── launch_otext_bg.xml
│ │ ├── search_btn.xml
│ │ └── skin_img_item_background.xml
│ ├── layout/
│ │ ├── about_me_fragment.xml
│ │ ├── addcity_activity.xml
│ │ ├── bg_pic_grid_item.xml
│ │ ├── change_background_fragment.xml
│ │ ├── citymanager_activity.xml
│ │ ├── exitapp_dialog.xml
│ │ ├── gridview_activity.xml
│ │ ├── gridview_citymanager.xml
│ │ ├── gridview_todaycan.xml
│ │ ├── homepager_activity.xml
│ │ ├── include_content_activity.xml
│ │ ├── include_title_activity.xml
│ │ ├── item_gridview_addcity.xml
│ │ ├── item_gridview_citymanager.xml
│ │ ├── item_gridview_todaycan.xml
│ │ ├── item_listview_tomorrow.xml
│ │ ├── main_activity.xml
│ │ ├── main_activity_net_error.xml
│ │ ├── tomorrow_weather_activity.xml
│ │ └── welcome_activity.xml
│ ├── values/
│ │ ├── attrs.xml
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ ├── values-sw600dp/
│ │ └── dimens.xml
│ ├── values-sw720dp-land/
│ │ └── dimens.xml
│ ├── values-v11/
│ │ └── styles.xml
│ └── values-v14/
│ └── styles.xml
└── src/
└── com/
└── htq/
└── coolweather/
├── AboutMeFragment.java
├── AddCityActivity.java
├── ChangeBackgroundFragment.java
├── CityManagerActivity.java
├── CityManagerFragment.java
├── FragmentAndActivity.java
├── HomePageFragment.java
├── LifeIndexFragment.java
├── MainActivity.java
├── WelcomeActivity.java
├── adapter/
│ ├── BgPicGridAdapter.java
│ ├── GridAddCityAdapter.java
│ ├── GridCityMAdapter.java
│ ├── GridTodayCAdapter.java
│ └── ListWeatherAdapter.java
├── base/
│ ├── Appliction.java
│ ├── AutoLocation.java
│ ├── CHImageView.java
│ ├── MHttpEntity.java
│ ├── SQLiteCityManager.java
│ └── SendDataEntity.java
├── entity/
│ ├── BgPicEntity.java
│ ├── CityManagerEntity.java
│ ├── LivingIndexEntity.java
│ ├── MHttpEntity.java
│ ├── ResponseWrapper.java
│ ├── SQLiteCityManager.java
│ ├── SendDataEntity.java
│ ├── WeatherEntity.java
│ └── WeatherSubEntity.java
└── utils/
├── CircleImageView.java
├── SharePrefrenceUtil.java
└── SystemUtils.java
================================================
FILE CONTENTS
================================================
================================================
FILE: .classpath
================================================
================================================
FILE: .project
================================================
CoolWeather
com.android.ide.eclipse.adt.ResourceManagerBuilder
com.android.ide.eclipse.adt.PreCompilerBuilder
org.eclipse.jdt.core.javabuilder
com.android.ide.eclipse.adt.ApkBuilder
com.android.ide.eclipse.adt.AndroidNature
org.eclipse.jdt.core.javanature
================================================
FILE: .settings/org.eclipse.jdt.core.prefs
================================================
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
org.eclipse.jdt.core.compiler.compliance=1.6
org.eclipse.jdt.core.compiler.source=1.6
================================================
FILE: AndroidManifest.xml
================================================
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README.md
================================================
# CoolWeather
本人完全自主设计与开发的一款轻量级简约好用的天气App,无广告,无烦人的通知栏,定位精准,天气信息数据准确,还支持更换背景皮肤哦,颜值爆表,如要引用,请注明出处:https://github.com/HuTianQi/CoolWeather
实现的功能:
1自动定位:自动获取用户所在的城市位置然后显示该位置的天气情况
2手动查询:如果定位失败,用户可以手动输入城市名查询天气
3城市管理:用户可以添加/删除多个城市,方便用户在不同城市直接查看该城市的天气
4生活指数:提醒用户生活方面的一些指数信息,如穿衣,是否适合外出
5自动换肤:能够根据用户所在城市的当天天气自动更换背景皮肤,如雨天则显示下雨的背景皮肤。晴天则显示蓝天白云的背景皮肤
6更换皮肤:用户可以在更换皮肤模块选择自己喜欢的图片作为该App主界面的皮肤,悄悄地告诉颖火虫们,内置了一张我们的颖宝宝的美图哦
7分享功能:如果用户觉得该App不错,可以将其分享到QQ好友或微博,微信朋友圈等社交场合
如果大家觉得不错,欢迎大家访问关注我的博客账号:http://blog.csdn.net/htq__
该App已在各大app Market上线:评分均为7.5分及以上
百度手机助手
360手机助手
应用截图:界面是不是很美呢?










#相关链接
【QQ:一款高仿腾讯QQ的IM App,已经实现了纯文本,表情,图片,位置,语音等信息的发送以及增,删,查好友等功能,代码质量非常高】[https://github.com/HuTianQi/QQ](https://github.com/HuTianQi/QQ)
【HQ_QQ:一款高仿腾讯QQ的IM通讯App,界面几乎与腾讯QQ一模一样】 https://github.com/HuTianQi/HTQ_QQ
【美女笔记:一款类似印象笔记的App】https://github.com/HuTianQi/YingBeautyNote
#LICENSE
The MIT License (MIT)
Copyright (c) 2016 HuTianQi
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
================================================
FILE: lint.xml
================================================
================================================
FILE: proguard-project.txt
================================================
# To enable ProGuard in your project, edit project.properties
# to define the proguard.config property as described in that file.
#
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in ${sdk.dir}/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the ProGuard
# include property in project.properties.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
================================================
FILE: project.properties
================================================
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system edit
# "ant.properties", and override values to adapt the script to your
# project structure.
#
# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
# Project target.
target=android-19
================================================
FILE: res/drawable/citym_normal_bg.xml
================================================
================================================
FILE: res/drawable/citym_normal_color.xml
================================================
================================================
FILE: res/drawable/drawerlayout_bt_bg.xml
================================================
================================================
FILE: res/drawable/drawerlayout_button_bg.xml
================================================
================================================
FILE: res/drawable/exitapp_text_bg.xml
================================================
================================================
FILE: res/drawable/homep_search_bg.xml
================================================
================================================
FILE: res/drawable/homep_titlebt_bg.xml
================================================
================================================
FILE: res/drawable/homep_titlemenu_bg.xml
================================================
================================================
FILE: res/drawable/inputcity_edit.xml
================================================
================================================
FILE: res/drawable/item_citym_normal_bg.xml
================================================
================================================
FILE: res/drawable/item_citym_normal_color.xml
================================================
================================================
FILE: res/drawable/item_todayc_bg.xml
================================================
================================================
FILE: res/drawable/launch_otext_bg.xml
================================================
================================================
FILE: res/drawable/search_btn.xml
================================================
================================================
FILE: res/drawable/skin_img_item_background.xml
================================================
================================================
FILE: res/layout/about_me_fragment.xml
================================================
================================================
FILE: res/layout/addcity_activity.xml
================================================
================================================
FILE: res/layout/bg_pic_grid_item.xml
================================================
================================================
FILE: res/layout/change_background_fragment.xml
================================================
================================================
FILE: res/layout/citymanager_activity.xml
================================================
================================================
FILE: res/layout/exitapp_dialog.xml
================================================
================================================
FILE: res/layout/gridview_activity.xml
================================================
================================================
FILE: res/layout/gridview_citymanager.xml
================================================
================================================
FILE: res/layout/gridview_todaycan.xml
================================================
================================================
FILE: res/layout/homepager_activity.xml
================================================
================================================
FILE: res/layout/include_content_activity.xml
================================================
================================================
FILE: res/layout/include_title_activity.xml
================================================
================================================
FILE: res/layout/item_gridview_addcity.xml
================================================
================================================
FILE: res/layout/item_gridview_citymanager.xml
================================================
================================================
FILE: res/layout/item_gridview_todaycan.xml
================================================
================================================
FILE: res/layout/item_listview_tomorrow.xml
================================================
================================================
FILE: res/layout/main_activity.xml
================================================
================================================
FILE: res/layout/main_activity_net_error.xml
================================================
================================================
FILE: res/layout/tomorrow_weather_activity.xml
================================================
================================================
FILE: res/layout/welcome_activity.xml
================================================
================================================
FILE: res/values/attrs.xml
================================================
================================================
FILE: res/values/dimens.xml
================================================
16dp
16dp
================================================
FILE: res/values/strings.xml
================================================
酷我天气
酷我天气 @:htq All rights reserved
作者:@:htq 爱丽颖的颖火虫
blog:http://blog.csdn.net/htq__欢迎大家访问我的博客
生活指数
天气预报
请输入城市名:
查询
城市管理
空气清新
空气良好
轻度污染
中度污染
重度污染
请输入城市名
网络请求失败
再次按下程序退出
暂无数据
#00FF00
#00FFFF
#FF9F00
#FF0000
#000000
#B3D7F3
#888888
获取数据失败
请输入正确的城市名
武汉
设为默认
简约 好用的天气APP
热门城市
加载中
================================================
FILE: res/values/styles.xml
================================================
================================================
FILE: res/values-sw600dp/dimens.xml
================================================
================================================
FILE: res/values-sw720dp-land/dimens.xml
================================================
128dp
================================================
FILE: res/values-v11/styles.xml
================================================
================================================
FILE: res/values-v14/styles.xml
================================================
================================================
FILE: src/com/htq/coolweather/AboutMeFragment.java
================================================
package com.htq.coolweather;
import com.htq.coolweather.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.util.Linkify;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class AboutMeFragment extends Fragment {
private View baseView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// TODO Auto-generated method stub
baseView=inflater.inflate(R.layout.about_me_fragment, null);
initView();
return baseView;
}
private void initView()
{
TextView aboutMeTv=(TextView) baseView.findViewById(R.id.about_me_tv);
Linkify.addLinks(aboutMeTv, Linkify.ALL);
}
}
================================================
FILE: src/com/htq/coolweather/AddCityActivity.java
================================================
package com.htq.coolweather;
import com.htq.coolweather.R;
import com.htq.coolweather.adapter.GridAddCityAdapter;
import com.htq.coolweather.entity.SQLiteCityManager;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
/**
*
* @author htq 爱丽颖的颖火虫
* blog:blog.csdn.net/htq__
*/
public class AddCityActivity extends Activity {
private GridView addCityGrid;
private static TextView cityTv;
private boolean ishas;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addcity_activity);
initView();
}
private void initView()
{
addCityGrid = (GridView) findViewById(R.id.addcity_gridview);
GridAddCityAdapter ad = new GridAddCityAdapter(this);
addCityGrid.setAdapter(ad);
addCityGrid.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view,
int position, long id) {
cityTv = (TextView) view.findViewById(R.id.citytext);
cityTv.setCompoundDrawablesWithIntrinsicBounds(0, 0,
R.drawable.city_checkbox_selected, 0);
querydata(cityTv.getText().toString());
// 如果数据库中没有该城市,则添加到数据库。反之则提示。
if(!ishas){
insertdata();
finish();
}else{
Toast.makeText(AddCityActivity.this, "不可重复添加",
Toast.LENGTH_SHORT).show();
}
}
});
}
private SQLiteCityManager sqlite = new SQLiteCityManager(
AddCityActivity.this, "weatherdb", null, 1);
private void insertdata() {
SQLiteDatabase db = sqlite.getReadableDatabase();
ContentValues cv = new ContentValues();
cv.put("cityname", cityTv.getText().toString());
cv.put("imageurl", "");
cv.put("weather", "点击更新");
cv.put("temp", "0℃");
//
db.insert("coolWeather", "cityname", cv);
}
public void querydata(String str) {
// 读写数据库
SQLiteDatabase db = sqlite.getReadableDatabase();
Cursor cursor = db.query("coolWeather", null, null, null, null, null,
null);
while (cursor.moveToNext()) {
String cityname = cursor.getString(cursor
.getColumnIndex("cityname"));
cityname = cityname.substring(0, 2);
str = str.substring(0, 2);
// 与当前按下的城市名做比较
if (ishas = cityname.equals(str)) {
return;
}
}
}
}
================================================
FILE: src/com/htq/coolweather/ChangeBackgroundFragment.java
================================================
package com.htq.coolweather;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import com.htq.coolweather.R;
import com.htq.coolweather.adapter.BgPicGridAdapter;
import com.htq.coolweather.entity.BgPicEntity;
import com.htq.coolweather.utils.SharePrefrenceUtil;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.RelativeLayout;
public class ChangeBackgroundFragment extends Fragment {
private List mBgPicList;
private View baseView;
private GridView mGridView;
private BgPicGridAdapter mBgPicAdapter;
private SharePrefrenceUtil shareUtil;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreateView(inflater, container, savedInstanceState);
baseView=inflater.inflate(R.layout.change_background_fragment, null);
initBackgroundPic();
initView();
return baseView;
}
private void initView()
{
mGridView = (GridView) baseView.findViewById(R.id.change_background_grid);
mBgPicAdapter = new BgPicGridAdapter(getActivity(),mBgPicList);
mGridView.setOnItemClickListener(gridItemClickListener);
mGridView.setAdapter(mBgPicAdapter);
}
private void initBackgroundPic()
{
AssetManager am = getActivity().getAssets();
try {
String[] drawableList = am.list("bkgs");
mBgPicList = new ArrayList();
for (String path : drawableList) {
BgPicEntity bg = new BgPicEntity();
InputStream is = am.open("bkgs/" + path);
Bitmap bitmap = BitmapFactory.decodeStream(is);
bg.path = path;
bg.bitmap = bitmap;
mBgPicList.add(bg);
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
OnItemClickListener gridItemClickListener=new OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
// TODO Auto-generated method stub
String path = ((BgPicEntity)mBgPicAdapter.getItem(position)).path;
shareUtil=new SharePrefrenceUtil(getActivity());
shareUtil.saveBgPicPath(path);
Log.i("weatherIndex",path);
// Drawable drawable=Drawable.createFromPath(path);
// mMainLayout.setBackgroundDrawable(drawable);
// Bitmap bitmap =getBitmapByPath(path);
// if(bitmap != null) {
// mMainLayout.setBackgroundDrawable(new BitmapDrawable(getActivity().getResources(), bitmap));
// }
Intent intent=new Intent("change_background");
intent.putExtra("path", path);
getActivity().sendBroadcast(intent);
mBgPicAdapter.notifyDataSetChanged();
}
};
}
================================================
FILE: src/com/htq/coolweather/CityManagerActivity.java
================================================
package com.htq.coolweather;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.util.VersionInfo;
import com.htq.coolweather.R;
import com.htq.coolweather.adapter.GridCityMAdapter;
import com.htq.coolweather.entity.CityManagerEntity;
import android.app.Activity;
import android.os.Bundle;
import android.widget.GridView;
public class CityManagerActivity extends Activity {
private GridView mGrid;
private List mCityManagerEntity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview_activity);
initView();
}
private void initView()
{
mCityManagerEntity = new ArrayList();
mGrid = (GridView) findViewById(R.id.gridview);
mGrid.setNumColumns(3);
mGrid.setBackgroundResource(R.drawable.bg_homepager_blur);
mGrid.setAdapter(new GridCityMAdapter(this, mCityManagerEntity));
}
}
================================================
FILE: src/com/htq/coolweather/CityManagerFragment.java
================================================
package com.htq.coolweather;
import com.htq.coolweather.R;
import com.htq.coolweather.adapter.GridCityMAdapter;
import com.htq.coolweather.entity.CityManagerEntity;
import com.htq.coolweather.entity.SQLiteCityManager;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
public class CityManagerFragment extends Fragment {
public static final String TAG = "CityManager";
private GridView mGridview;
private String cityname;
private String imageurl;
private String weather;
private String temp;
public CityManagerEntity cmb;
public GridCityMAdapter cmAdapter;
private FragmentAndActivity mActivity;
public Intent intent;
private SQLiteCityManager sqlite;
private SQLiteDatabase db;
private View baseView;
@Override
public void onResume() {
getdatabase();
for (int i = 0; i < HomePageFragment.mcmb.size(); i++) {
if (HomePageFragment.mcmb.get(i).getCity()
.equals(MainActivity.cmb2.getCity())) {
HomePageFragment.mcmb.remove(MainActivity.cmb2);
}
}
// 标记,为每次打开城市管理页都会加载一个item问题的解决方案
MainActivity.cmb2.setCity("添加");
HomePageFragment.mcmb.add(HomePageFragment.mcmb.size(),
MainActivity.cmb2);
cmAdapter.setCitymanager(HomePageFragment.mcmb);
for(int i = 0; i < HomePageFragment.mcmb.size(); i++ ){
Log.i("TAG", HomePageFragment.mcmb.get(i).getCity());
}
Log.i("TAG", HomePageFragment.mcmb.size()+"<<<<==>>>>HomePageFragment.mcmb");
cmAdapter.notifyDataSetChanged();
super.onResume();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mActivity = (FragmentAndActivity) activity;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
MainActivity.TAG_H = TAG;
baseView=inflater.inflate(R.layout.gridview_citymanager,
null);
init();
return baseView;
}
private void init()
{
mGridview = (GridView) baseView.findViewById(R.id.gridview);
intent = new Intent(getActivity(), AddCityActivity.class);
mGridview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view,
int position, long id) {
if (position == HomePageFragment.mcmb.size() - 1) {
startActivity(intent);
} else {
//showDialog
mActivity.showDialog();
MainActivity ff = (MainActivity) getActivity();
ff.switchFragment(MainActivity.homecontent,
HomePageFragment.TAG);
// 得到城市,发起网络请求。
mActivity.sendcitytext(HomePageFragment.mcmb.get(
position).getCity());
}
}
});
cmAdapter = new GridCityMAdapter(getActivity(),
HomePageFragment.mcmb);
mGridview.setAdapter(cmAdapter);
}
public void getdatabase() {
sqlite = new SQLiteCityManager(getActivity(),
"weatherdb", null, 1);
db = sqlite.getWritableDatabase();
Cursor cursor = db.query("coolWeather", null, null, null, null, null,
null);
HomePageFragment.mcmb.clear();
while (cursor.moveToNext()) {
int _id = cursor.getInt(cursor.getColumnIndex("_id"));
cityname = cursor.getString(cursor.getColumnIndex("cityname"));
imageurl = cursor.getString(cursor.getColumnIndex("imageurl"));
weather = cursor.getString(cursor.getColumnIndex("weather"));
temp = cursor.getString(cursor.getColumnIndex("temp"));
Log.i("TAG", _id + " @@@@@@@@_id-" + " cityname-" + cityname + " imageurl-"
+ imageurl + " weather-" + weather + " temp-" + temp);
setCityManagerEntity();
}
}
public void setCityManagerEntity() {
cmb = new CityManagerEntity();
cmb.setCity(cityname);
cmb.setWeather(weather);
cmb.setTemp(temp);
cmb.setWeatherimage(imageurl);
for (int i = 0; i < HomePageFragment.mcmb.size(); i++) {
Log.i("TAG", HomePageFragment.mcmb.size()+"==>HomePageFragment.mcmb.size()");
Log.i("TAG", HomePageFragment.mcmb.get(i).getCity()+"==>" +
"HomePageFragment.mcmb.get(i).getCity()");
if (HomePageFragment.mcmb.get(i).getCity().equals(cmb.getCity())) {
HomePageFragment.mcmb.set(i, cmb);
return;
}
}
HomePageFragment.mcmb.add(cmb);
}
/**
* 删除数据库
*/
public void deletedata(){
sqlite = new SQLiteCityManager(getActivity(),
"weatherdb", null, 1);
db = sqlite.getWritableDatabase();
db.delete("coolWeather", "_id = "+ 2, null);
}
}
================================================
FILE: src/com/htq/coolweather/FragmentAndActivity.java
================================================
package com.htq.coolweather;
import android.widget.EditText;
public interface FragmentAndActivity {
public void senddata(EditText inputcity);
public void sendcitytext(String inputcitytext);
public void showDialog();
}
================================================
FILE: src/com/htq/coolweather/HomePageFragment.java
================================================
package com.htq.coolweather;
import java.util.ArrayList;
import java.util.List;
import com.htq.coolweather.R;
import com.htq.coolweather.adapter.ListWeatherAdapter;
import com.htq.coolweather.entity.CityManagerEntity;
import com.htq.coolweather.entity.SQLiteCityManager;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class HomePageFragment extends Fragment {
public static final String TAG = "HomeContent";
public static List mcmb = new ArrayList();
public static TextView currentcity;// 当前城市
private TextView pm25;// PM值
private TextView temp;// 温度
private TextView pollution;// 污染程度
private ListView weatherInfolist;//
private EditText inputcity;
private Button searchWeatherBtn;
private View homeContent;
public MainActivity mainActivity;
public FragmentAndActivity mActivity;
static ProgressDialog pDialog;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
MainActivity.TAG_H = TAG;
if(!mainActivity.netErrorFlag)
{
homeContent = inflater.inflate(R.layout.include_content_activity,
null);
initview();
if(MainActivity.response.getResults()!=null)
{
setpagedata();
}
}
else{
homeContent = inflater.inflate(R.layout.main_activity_net_error,
null);
}
return homeContent;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mainActivity = (MainActivity) getActivity();
mActivity = (FragmentAndActivity) activity;
}
private void initview() {
currentcity = (TextView) homeContent.findViewById(R.id.currentcity);
pm25 = (TextView) homeContent.findViewById(R.id.pm25);
temp = (TextView) homeContent.findViewById(R.id.temp);
searchWeatherBtn= (Button) homeContent.findViewById(R.id.btn_search);
pollution = (TextView) homeContent.findViewById(R.id.pollution_level);
inputcity = (EditText) homeContent.findViewById(R.id.inputcity);
weatherInfolist = (ListView) homeContent
.findViewById(R.id.weather_infor_list);
}
/**
* @author htq
* 根据天气情况自动更换app的皮肤,如晴天则显示晴天的背景,多云则显示多云的背景...
* 如果当前天气为一种转另外一种天气,则显示前面的那种天气背景,如多云转晴则显示多云的背景
* 注自动设置背景不会在配置文件中记录设置的是哪张图片背景,仅仅当用户在更换皮肤模块手动更改才
* 在配置文件中记录
* bolg:blog.csdn.net/htq__
*/
private void autoSetBgPic()
{
String path=null;
String weather=MainActivity.response.getResults().get(0)
.getWeather_data().get(0).getWeather();
if(weather.contains("多云")&&!weather.contains("转多云"))
{
path="cloudy.jpg";
}else if(weather.contains("晴")&&!weather.contains("转晴"))
{
path="fine.jpg";
}else if(weather.contains("雨")){
path="rain.jpg";
}
if(path!=null)
{
Intent intent=new Intent("change_background");
intent.putExtra("path", path);
intent.putExtra("auto", true);
getActivity().sendBroadcast(intent);
}
}
public void setpagedata() {
if(pDialog != null){
pDialog.dismiss();
}
autoSetBgPic();
// Log.i("weather","autoSet is called");
weatherInfolist.setAdapter(new ListWeatherAdapter(getActivity(),
MainActivity.response.getResults().get(0)
.getWeather_data()));
searchWeatherBtn.setOnClickListener(searchWeatherOnClickListener);
currentcity.setText(MainActivity.response.getResults().get(0)
.getCurrentCity());
if ("".equals(MainActivity.response.getResults().get(0).getPm25())) {
pm25.setText("PM2.5:");
pollution.setText(R.string.no_data);
pollution.setBackgroundColor(Color.TRANSPARENT);
} else {
pm25.setText("PM2.5:"
+ MainActivity.response.getResults().get(0).getPm25());
int pm = Integer.parseInt(MainActivity.response.getResults()
.get(0).getPm25());
Log.i("TAG", pm + " <-- pm");
if (pm < 75) {
pollution.setText(R.string.pollution_no);
pollution.setBackgroundResource(R.drawable.ic_dl_b);
} else if (pm > 75 && pm < 100) {
pollution.setText(R.string.pollution_little);
pollution.setBackgroundResource(R.drawable.ic_dl_c);
} else if (pm > 100 && pm < 150) {
pollution.setText(R.string.pollution_mild);
pollution.setBackgroundResource(R.drawable.ic_dl_d);
} else if (pm > 150 && pm < 200) {
pollution.setText(R.string.polltion_moderate);
pollution.setBackgroundResource(R.drawable.ic_dl_e);
} else if (pm > 200) {
pollution.setText(R.string.polltion_severe);
pollution.setBackgroundResource(R.drawable.ic_dl_f);
}
}
String todaydata = MainActivity.response.getResults().get(0)
.getWeather_data().get(0).getDate();
String temperature = MainActivity.response.getResults().get(0)
.getWeather_data().get(0).getTemperature();
String subs = null;
if (todaydata.length() > 14) {
subs = todaydata.substring(14, todaydata.length() - 1);
temp.setText(subs);
} else if (temperature.length() > 5) {
String[] str = temperature.split("~ ", 2);
subs = str[1];
temp.setText(subs);
} else {
temp.setText(temperature);
}
// 创建SQLite对象并不会创建数据库
SQLiteCityManager sqlite = new SQLiteCityManager(getActivity(),
"weatherdb", null, 1);
// 读写数据库
SQLiteDatabase db = sqlite.getWritableDatabase();
// ContentValues键值对,类似HashMap
ContentValues cv = new ContentValues();
// key为字段名,value为所存数据
cv.put("cityname", MainActivity.response.getResults().get(0)
.getCurrentCity());
cv.put("imageurl", MainActivity.response.getResults().get(0)
.getWeather_data().get(0).getDayPictureUrl());
cv.put("weather", MainActivity.response.getResults().get(0)
.getWeather_data().get(0).getWeather());
cv.put("temp", subs);
Cursor cursor = db.query("coolWeather", null, null, null, null, null,
null);
int i = 0;
while (cursor.moveToNext()) {
i++;
Log.i("TAG", i + "==>>i");
String cityname = cursor.getString(cursor
.getColumnIndex("cityname"));
String weathertext = cursor.getString(cursor
.getColumnIndex("weather"));
cityname = cityname.substring(0, 2);
String citytext = currentcity.getText().toString().substring(0, 2);
if (citytext.equals(cityname)) {
if ("点击更新".equals(weathertext)) {
db.update("coolWeather", cv, "weather = ?",
new String[] { "点击更新" });
db.close();
}
return;
}
}
// 插入,第二个参数:不能为null的字段
db.insert("coolWeather", "cityname", cv);
db.close();
}
private View.OnClickListener searchWeatherOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
pDialog = new ProgressDialog(getActivity());
pDialog.setCancelable(true);// 点击可以取消Dialog的展现
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setMessage("正在查询,请稍后...");
pDialog.show();
mActivity.senddata(inputcity);
mActivity.sendcitytext(inputcity.getText().toString());
}
};
}
================================================
FILE: src/com/htq/coolweather/LifeIndexFragment.java
================================================
package com.htq.coolweather;
import java.util.Calendar;
import java.util.List;
import com.htq.coolweather.R;
import com.htq.coolweather.adapter.GridTodayCAdapter;
import com.htq.coolweather.entity.LivingIndexEntity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
/**
*
* @author htq 爱丽颖的颖火虫
* 博客地址:blog.csdn.net/htq__
*
*/
public class LifeIndexFragment extends Fragment {
public static final String TAG = "TodayCan";
public TextView descTv;
public List listsib;
private TextView dateTv;
private View baseView;
private GridView todayInfoGrid;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
MainActivity.TAG_H = TAG;
baseView = inflater.inflate(R.layout.gridview_todaycan, null);
initView();
initData();
return baseView;
}
private void initView()
{
todayInfoGrid = (GridView) baseView
.findViewById(R.id.gridview);
dateTv=(TextView) baseView.findViewById(R.id.date_tv);
descTv = (TextView)baseView.findViewById(R.id.todaycan_dec);
}
private void initData()
{
initDate();
if(MainActivity.response.getResults()==null)
{
Toast.makeText(getActivity(), "获取指数信息失败,请检查网络连接",0).show();
}else
{
setData();
}
}
private void setData()
{
listsib = MainActivity.response.getResults().get(0).getIndex();
// Log.i("weatherIndex", listsib.toString()+"==>>listsib.toString()");
if (MainActivity.response.getResults().get(0).getIndex()
.toString() == "[]") {
}else {
todayInfoGrid.setAdapter(new GridTodayCAdapter(getActivity(),
listsib));
}
todayInfoGrid.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view,
int position, long id) {
descTv.setText(listsib.get(position).getDes());
}
});
}
private void initDate()
{
Calendar calendar = Calendar.getInstance();
int year=calendar.get(Calendar.YEAR);
int mon=calendar.get(Calendar.MONTH )+1;
int day=calendar.get(Calendar.DAY_OF_MONTH);
dateTv.setText(year+"年"+mon+"月"+day+"日");
}
}
================================================
FILE: src/com/htq/coolweather/MainActivity.java
================================================
package com.htq.coolweather;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.ParseException;
import org.apache.http.util.EntityUtils;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.htq.coolweather.R;
import com.google.gson.GsonBuilder;
import com.htq.coolweather.base.Appliction;
import com.htq.coolweather.entity.CityManagerEntity;
import com.htq.coolweather.entity.MHttpEntity;
import com.htq.coolweather.entity.ResponseWrapper;
import com.htq.coolweather.entity.SendDataEntity;
import com.htq.coolweather.utils.SharePrefrenceUtil;
import com.htq.coolweather.utils.SystemUtils;
/**
*
* @author htq 爱丽颖的颖火虫
* 博客地址:blog.csdn.net/htq__
*
*/
public class MainActivity extends FragmentActivity implements
OnClickListener, FragmentAndActivity {
private long nowtime;
public static ResponseWrapper response = new ResponseWrapper();// 数据结构的对象
public static ResponseWrapper response2;
private DrawerLayout mainDrawerLayout;
private View leftDrawer;
private EditText inputcity;
public boolean netErrorFlag=false;
public static final int succeed = 1;
public static final int fail = 2;
public static final int nonet = 3;
private static int tag = 0;
public static String TAG_H = null;
private ProgressDialog pDialog;
public static HomePageFragment homecontent = new HomePageFragment();
public CityManagerFragment citymanager = new CityManagerFragment();
public static CityManagerEntity cmb2 = new CityManagerEntity();
private ChangeBgReceiver mReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
getIntentData();
registerBroadCast();
initview();
}
private void getIntentData()
{
Intent intent = getIntent();
String wetherdata = intent.getStringExtra("weather_data");// 得到启动页传递过来的数据
GsonBuilder gson = new GsonBuilder();//
response2 = gson.create().fromJson(wetherdata, ResponseWrapper.class);
if(response2!=null)
{
if(response2.getError() == 0){
response = response2;
}
}else
{
netErrorFlag=true;
}
}
private void initview() {
mainDrawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout_main);
initBgPic();
leftDrawer = findViewById(R.id.left_drawer);
mainDrawerLayout.setScrimColor(0x00000000);// 设置底部页面背景透明度
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragmentlayout, homecontent, HomePageFragment.TAG);
ft.commit();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.homep_menu:
switchLeftLayout();
break;
case R.id.homep_refresh:
if(Appliction.isNetWorkConnect(getApplicationContext()))
{
refresh();
}else {
Toast.makeText(getApplicationContext(), "网络未连接,请检查网络设置",0).show();
}
break;
case R.id.btn_life:
switchLeftLayout();
switchFragment(new LifeIndexFragment(),null);
break;
case R.id.btn_city_manager:
switchLeftLayout();
switchFragment(citymanager, null);
break;
case R.id.btn_change_bag:
switchLeftLayout();
switchFragment(new ChangeBackgroundFragment(), null);
break;
case R.id.btn_about:
switchLeftLayout();
switchFragment(new AboutMeFragment(), null);
break;
case R.id.btn_share_app:
SystemUtils.shareApp(this);
break;
case R.id.exitapp:
showExitDialog();
break;
}
}
private void refresh()
{
showDialog();
switchFragment(homecontent, null);
new Thread(new Runnable() {
@Override
public void run() {
sendRequest(HomePageFragment.currentcity.getText()
.toString());
}
}).start();
}
private void showExitDialog()
{
final Dialog dialog = new Dialog(this,
android.R.style.Theme_DeviceDefault_Dialog_NoActionBar);
View exitappview = getLayoutInflater().inflate
(R.layout.exitapp_dialog, null);
TextView exitapp_text = (TextView) exitappview.findViewById(R.id.exitapp_text);
Button leftbutton = (Button) exitappview.findViewById(R.id.leftbutton);
Button rightbutton = (Button) exitappview.findViewById(R.id.rightbutton);
exitapp_text.setText("退出程序");
leftbutton.setText("确定");
rightbutton.setText("取消");
leftbutton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
rightbutton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.setContentView(exitappview);
dialog.show();
}
private void fromJson(String wetherdata) {
GsonBuilder gson = new GsonBuilder();//
response2 = gson.create().fromJson(wetherdata, ResponseWrapper.class);
if (response2.getError() == 0) {
response = response2;
homecontent.setpagedata();
if (tag == 4 && inputcity != null) {
closeinput(inputcity);
}
} else if (response2.getError() == -3 || response2.getError() == -2) {
showToast(getString(R.string.input_truename));
} else {
showToast(getString(R.string.getdata_fail));
}
if(HomePageFragment.pDialog != null){
HomePageFragment.pDialog.dismiss();
}
}
/**
* 点击多次bt,Toast只显示一次的解决方案
*/
public Toast toast = null;
public void showToast(String text) {
if (toast == null) {
toast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
} else {
toast.setText(text);
}
toast.show();
}
/**
* 向服务器发送数据请求
*/
public void sendRequest(String cityname) {
String getData = null;
MHttpEntity mhe = null;
try {
SendDataEntity.setCity(cityname);// 获取用户输入的城市名
mhe = MHttpEntity.sendHttpRequest(SendDataEntity.getData());
if (mhe.getHentity() != null) {
getData = EntityUtils.toString(mhe.getHentity());
mhe.getMessage().obj = getData;
}
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
handler.sendMessage(mhe.getMessage());// 使用Handler对网络状态做处理
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (pDialog != null)
pDialog.dismiss();
if (msg != null)
switch (msg.arg1) {
case succeed:// 与服务器连接成功
if (msg.obj != null) {
fromJson(msg.obj.toString());
}
break;
case fail:// 与服务器连接失败
showToast(getString(R.string.net_fail));
break;
}
}
};
/**
* 关联menu键
*/
private void switchLeftLayout() {
if (mainDrawerLayout.isDrawerOpen(leftDrawer)) {
mainDrawerLayout.closeDrawer(leftDrawer);
} else {
mainDrawerLayout.openDrawer(leftDrawer);
}
}
public void switchFragment(Fragment fragment, String str) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragmentlayout, fragment, null);
//ft.replace(R.id.fragmentlayout, fragment, str);
ft.commit();
}
/**
* 关闭输入法键盘
*/
public void closeinput(EditText editText) {
editText.setText("");
InputMethodManager imm = (InputMethodManager)
getSystemService(MainActivity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
/**
* 连续按两次返回则退出程序
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (System.currentTimeMillis() - nowtime > 2000) {
Toast.makeText(this, R.string.click_exit, Toast.LENGTH_SHORT)
.show();
nowtime = System.currentTimeMillis();
return true;
} else {
finish();
}
}
return super.onKeyDown(keyCode, event);
}
@Override
public void senddata(EditText inputcity) {
this.inputcity = inputcity;
}
@Override
public void sendcitytext(final String inputcitytext) {
// this.inputcitytext = inputcitytext;
tag = 4;
if ("".equals(inputcitytext)) {
showToast(getString(R.string.edittext_hint));
if(HomePageFragment.pDialog != null){
HomePageFragment.pDialog.dismiss();
}
} else {
SendDataEntity.setCity(inputcitytext);// 获取用户输入城市
new Thread(new Runnable() {
@Override
public void run() {
sendRequest(inputcitytext);
}
}).start();
}
}
private void registerBroadCast()
{
mReceiver = new ChangeBgReceiver();
IntentFilter filter = new IntentFilter("change_background");
registerReceiver(mReceiver, filter);
}
private class ChangeBgReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String path = intent.getStringExtra("path");
if(path==null)
Log.i("weather", "path is null");
else
{
Log.i("weather", path);
}
boolean auto=intent.getBooleanExtra("auto",false);
Bitmap bitmap = getBitmapByPath(path,auto);
if(bitmap != null) {
mainDrawerLayout.setBackgroundDrawable(new BitmapDrawable(getResources(), bitmap));
}
}
}
public Bitmap getBitmapByPath(String path,boolean auto) {
// Log.i("weather", "getbitmap is called");
AssetManager am = this.getAssets();
Bitmap bitmap = null;
InputStream is =null;
try {
if(auto==false)
{
is = am.open("bkgs/" + path);
}else if(auto==true)
{
Log.i("weather", "before open auto_bkgs");
is = am.open("autobkgs/" + path);
Log.i("weather", path);
}
bitmap = BitmapFactory.decodeStream(is);
is.close();
} catch (IOException e) {
e.printStackTrace();
Log.i("weather", "open file error");
}
return bitmap;
}
@Override
public void showDialog() {
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setCancelable(true);// 点击可以取消Dialog的展现
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setMessage("正在更新...");
pDialog.show();
}
private void initBgPic()
{
String path=new SharePrefrenceUtil(this).getPath();
Intent intent=new Intent("change_background");
intent.putExtra("path", path);
sendBroadcast(intent);
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(mReceiver);
}
}
================================================
FILE: src/com/htq/coolweather/WelcomeActivity.java
================================================
package com.htq.coolweather;
import java.io.IOException;
import org.apache.http.ParseException;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.htq.coolweather.R;
import com.google.gson.GsonBuilder;
import com.htq.coolweather.entity.MHttpEntity;
import com.htq.coolweather.entity.ResponseWrapper;
import com.htq.coolweather.entity.SendDataEntity;
/**
* @author htq 爱丽颖的颖火虫
* 博客地址:bolg.csdn.net/htq__
*
*/
public class WelcomeActivity extends Activity {
public static ResponseWrapper response;// 数据结构的对象
public static final int succeed = 1;
public static final int fail = 2;
public static final int nonet = 3;
public String normalDistrict;
public String locationCity = "武汉";
public LocationClient mLocationClient = null;
public BDLocationListener mListener;
private ProgressDialog pDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome_activity);
initData();
}
private void initData()
{
showProgressDialog("自动定位中...");
initBaiduMapLocation();
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
sendRequest();
}
}).start();
}
private void initBaiduMapLocation()
{
mLocationClient = new LocationClient(this.getApplicationContext());
mListener = new MyLocationListener();
mLocationClient.registerLocationListener(mListener);// 娉ㄥ唽鐩戝惉鍑芥暟
LocationClientOption option = new LocationClientOption();
option.setLocationMode(LocationMode.Hight_Accuracy);
option.setIsNeedAddress(true);
mLocationClient.setLocOption(option);
mLocationClient.start();
}
private void showProgressDialog(String title)
{
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
pDialog.setMessage(title+"...");
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.show();
}
private void sendRequest() {
String getData = null;
MHttpEntity mhe = null;
try {
SendDataEntity.setCity(normalDistrict);
Log.e("TAG", normalDistrict + "==>>normalDistrict");
mhe = MHttpEntity.sendHttpRequest(SendDataEntity.getData());
if (mhe.getHentity() != null) {
getData = EntityUtils.toString(mhe.getHentity());
GsonBuilder gson = new GsonBuilder();//
response = gson.create().fromJson(getData,
ResponseWrapper.class);
Log.i("TAG", response.getError() + "-->response.getError()");
if (response.getError() == -3) {
SendDataEntity.setCity(normalDistrict);
mhe = MHttpEntity.sendHttpRequest(SendDataEntity.getData());
if (mhe.getHentity() != null) {
getData = EntityUtils.toString(mhe.getHentity());
Log.i("weather_info", getData + "-->getData");
}
if (response.getError() == -3) {
SendDataEntity.setCity(locationCity);
mhe = MHttpEntity
.sendHttpRequest(SendDataEntity.getData());
if (mhe.getHentity() != null) {
Log.e("TAG", mhe.getHentity() + "==>>mhe.getHentity()");
getData = EntityUtils.toString(mhe.getHentity());
}
}
}
mhe.getMessage().obj = getData;
}
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
handler.sendMessage(mhe.getMessage());// 使用Handler对网络状态做处理
}
/**
* 对网络连接状态做处理
*/
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if(pDialog != null){
pDialog.dismiss();
}
if (msg != null)
switch (msg.arg1) {
case succeed:// 与服务器连接成功,则传递数据并跳转
Intent intent = new Intent(WelcomeActivity.this,
MainActivity.class);
if (msg.obj != null)
intent.putExtra("weather_data", (String) msg.obj);
intent.putExtra("normal_city", locationCity);
startActivity(intent);
finish();
break;
case fail:// 与服务器连接失败,弹出错误提示Toast
Toast.makeText(WelcomeActivity.this,
getString(R.string.net_fail), Toast.LENGTH_SHORT)
.show();
intent = new Intent(WelcomeActivity.this,
MainActivity.class);
intent.putExtra("weather_data", (String) msg.obj);
startActivity(intent);
finish();
break;
}
}
};
/**
* 拦截返回键
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return true;
}
return super.onKeyDown(keyCode, event);
}
public class MyLocationListener implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
if (location != null) {
normalDistrict = location.getDistrict();
locationCity = location.getCity();
if(locationCity == null){
Toast.makeText(WelcomeActivity.this, "定位失败,请检查网络", Toast.LENGTH_SHORT).show();
}else{
String[] str = locationCity.split("市");
locationCity = str[0];
if("".equals(locationCity)){
Toast.makeText(WelcomeActivity.this, "定位失败,默认为武汉", Toast.LENGTH_LONG).show();
}
}
}
}
}
}
================================================
FILE: src/com/htq/coolweather/adapter/BgPicGridAdapter.java
================================================
package com.htq.coolweather.adapter;
import java.util.List;
import com.htq.coolweather.R;
import com.htq.coolweather.entity.BgPicEntity;
import com.htq.coolweather.utils.SharePrefrenceUtil;
import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
/**
*
* @author htq 爱丽颖的颖火虫
* 博客地址:blog.csdn.net/htq__
*/
public class BgPicGridAdapter extends BaseAdapter {
private List bgList;
private Resources resources;
private Activity mActivity;
private String mDefaultBgPath;
private SharePrefrenceUtil sharePrefrenceUtil;
public BgPicGridAdapter(Activity mActivity,List list)
{
this.bgList = list;
this.mActivity=mActivity;
this.resources = mActivity.getResources();
sharePrefrenceUtil=new SharePrefrenceUtil(mActivity);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return bgList.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return bgList.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(mActivity).inflate(
R.layout.bg_pic_grid_item, null);
viewHolder.backgroundIv = (ImageView) convertView
.findViewById(R.id.gridview_item_iv);
viewHolder.checkedIv = (ImageView) convertView
.findViewById(R.id.gridview_item_checked_iv);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.backgroundIv.setBackgroundDrawable(new BitmapDrawable(
resources, ((BgPicEntity)getItem(position)).bitmap));
mDefaultBgPath=sharePrefrenceUtil.getPath();
if (((BgPicEntity)getItem(position)).path.equals(mDefaultBgPath)) {
viewHolder.checkedIv.setVisibility(View.VISIBLE);
} else {
viewHolder.checkedIv.setVisibility(View.GONE);
}
return convertView;
}
private class ViewHolder {
ImageView checkedIv, backgroundIv;
}
}
================================================
FILE: src/com/htq/coolweather/adapter/GridAddCityAdapter.java
================================================
package com.htq.coolweather.adapter;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.htq.coolweather.R;
import com.htq.coolweather.entity.SQLiteCityManager;
public class GridAddCityAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private static final String[] cityname =
{ "北京", "上海", "广州","南京", "成都", "武汉", "杭州", "西安", "济南", "长春", "东莞",
"沈阳", "天津", "哈尔滨", "长沙", "呼和浩特", "石家庄", "重庆", "无锡", "包头",
"大连", "深圳", "福州", "海口", "乌鲁木齐", "兰州", "银川", "太原", "郑州",
"合肥", "南昌", "南宁", "贵阳", "昆明", "拉萨", "西宁", "台北", "香港", "澳门" };
SparseBooleanArray sba = new SparseBooleanArray();
private String nowcityname;
public GridAddCityAdapter(Context context) {
this.mInflater = LayoutInflater.from(context);
SQLiteCityManager sqlite = new SQLiteCityManager(context, "weatherdb", null, 1);
SQLiteDatabase db = sqlite.getReadableDatabase();
Cursor cursor = db.query("coolWeather", null, null, null, null, null, null);
while(cursor.moveToNext()){
nowcityname = cursor.getString(cursor.getColumnIndex("cityname"));
Log.i("TAG", nowcityname+"-->nowcityname");
for(int i=0;i citymanager;
private Context context;
private Dialog mDialog;
public GridCityMAdapter(Context context, List citymanager) {
this.context = context;
this.mInflater = LayoutInflater.from(context);
this.citymanager = citymanager;
}
@Override
public int getCount() {
return citymanager == null ? 0 : citymanager.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item_gridview_citymanager,
parent, false);
}
final TextView grid_city = (TextView) convertView
.findViewById(R.id.grid_city);
TextView grid_temp = (TextView) convertView
.findViewById(R.id.grid_temp);
CHImageView grid_weatherimage = (CHImageView) convertView
.findViewById(R.id.grid_weatherimage);
TextView grid_weather = (TextView) convertView
.findViewById(R.id.grid_weather);
Button grid_set_normal = (Button) convertView
.findViewById(R.id.grid_set_normal);
TextView city_item_layout = (TextView) convertView
.findViewById(R.id.city_item_layout);
TextView grid_item_delete = (TextView) convertView
.findViewById(R.id.grid_item_delete);
grid_item_delete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
mDialog = new Dialog(context,
android.R.style.Theme_DeviceDefault_Dialog_NoActionBar);
View deleteview = LayoutInflater.from(context).inflate(R.layout.exitapp_dialog, null);
TextView exitapp_text = (TextView) deleteview.findViewById(R.id.exitapp_text);
Button leftbutton = (Button) deleteview.findViewById(R.id.leftbutton);
Button rightbutton = (Button) deleteview.findViewById(R.id.rightbutton);
exitapp_text.setText("删除城市");
leftbutton.setText("确定");
rightbutton.setText("取消");
leftbutton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SQLiteCityManager sqlite = new SQLiteCityManager(context,
"weatherdb", null, 1);
SQLiteDatabase db = sqlite.getWritableDatabase();
String mcityname = grid_city.getText().toString();
int index = db.delete("coolWeather", "cityname = ?", new String []{mcityname});
if(index == 0){
Toast.makeText(context, "删除失败,请重试", Toast.LENGTH_SHORT).show();
}
mDialog.dismiss();
for(int i = 0; i < citymanager.size(); i++){
if(mcityname.equals(citymanager.get(i).getCity())){
citymanager.remove(i);
}
}
notifyDataSetChanged();
}
});
rightbutton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mDialog.dismiss();
}
});
mDialog.setContentView(deleteview);
mDialog.show();
}
});
grid_set_normal.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 设为默认的点击事件
}
});
if (position == citymanager.size() - 1) {
grid_city.setText("");
grid_temp.setText("");
grid_weather.setText("");
grid_set_normal.setText("");
grid_weatherimage.setImageDrawable(null);
grid_set_normal.setBackgroundColor(Color.TRANSPARENT);
city_item_layout.setBackgroundResource(R.drawable.cityadd_bg);
grid_item_delete.setText("");
} else {
grid_item_delete.setText("×");
grid_city.setText(citymanager.get(position).getCity());
grid_temp.setText(citymanager.get(position).getTemp());
grid_weatherimage.loadImage(citymanager.get(position)
.getWeatherimage());
grid_weather.setText(citymanager.get(position).getWeather());
grid_set_normal.setBackgroundResource(R.drawable.citym_normal_bg);
if (position == 0) {
grid_set_normal.setText("默认");
} else {
grid_set_normal.setText("设为默认");
}
city_item_layout.setBackgroundResource(Color.TRANSPARENT);
}
return convertView;
}
public void setCitymanager(List citymanager) {
this.citymanager = citymanager;
}
}
================================================
FILE: src/com/htq/coolweather/adapter/GridTodayCAdapter.java
================================================
package com.htq.coolweather.adapter;
import java.util.List;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.htq.coolweather.R;
import com.htq.coolweather.entity.LivingIndexEntity;
public class GridTodayCAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private List sportIndex;
private int[] resours = {
R.drawable.ic_todaycan_dress,
R.drawable.ic_todaycan_carwash, R.drawable.ic_todaycan_tour,
R.drawable.ic_todaycan_coldl, R.drawable.ic_todaycan_sport,
R.drawable.ic_todaycan_ultravioletrays };
public GridTodayCAdapter(Context context, List sportIndex) {
this.mInflater = LayoutInflater.from(context);
this.sportIndex = sportIndex;
}
@Override
public int getCount() {
return sportIndex == null ? 0 : sportIndex.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
// 此处需要加上第二个参数parent,否则item中的设置无效。如item高度设置。
convertView = mInflater.inflate(R.layout.item_gridview_todaycan,
parent, false);
}
TextView dothing = (TextView) convertView.findViewById(R.id.dothing);
TextView index = (TextView) convertView.findViewById(R.id.index);
ImageView image_index = (ImageView) convertView
.findViewById(R.id.image_index);
ImageView image_click = (ImageView) convertView
.findViewById(R.id.image_click);
// 设置数据
if (position == 0){
dothing.setText("穿衣指数");
}else if (position == 1) {
dothing.setText("洗车指数");
}else if (position == 2){
dothing.setText("旅游指数");
}else if (position == 3) {
dothing.setText("感冒指数");
}else if (position == 4) {
dothing.setText("运动指数");
}else if (position == 5) {
dothing.setText("紫外线指数");
}
else {
dothing.setText(sportIndex.get(position).getTipt());
}
index.setText("点击查看详情");
Log.i("TAG", sportIndex.size()+"sportIndex.size()");
image_index.setBackgroundResource(resours[position]);
image_click.setBackgroundResource(R.drawable.ic_todaycan_clickbt);
return convertView;
}
}
================================================
FILE: src/com/htq/coolweather/adapter/ListWeatherAdapter.java
================================================
package com.htq.coolweather.adapter;
import java.util.List;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.htq.coolweather.R;
import com.htq.coolweather.base.CHImageView;
import com.htq.coolweather.entity.WeatherSubEntity;
public class ListWeatherAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private List tweather;
public ListWeatherAdapter(Context context, List tweather) {
this.mInflater = LayoutInflater.from(context);
this.tweather = tweather;
}
@Override
public int getCount() {
return tweather == null ? 0 : tweather.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item_listview_tomorrow,
null);
}
// 日期
TextView list_date_nextday = (TextView) convertView
.findViewById(R.id.list_date_nextday);
if (position > 0) {
list_date_nextday.setText(tweather.get(position).getDate());
} else if (position == 0) {
list_date_nextday.setText("今天");
}
// 白天天气图片
CHImageView list_day_picture = (CHImageView) convertView
.findViewById(R.id.list_day_picture);
String dayp = tweather.get(position).getDayPictureUrl();
list_day_picture.loadImage(dayp);
// 夜晚天气图片
CHImageView list_night_picture = (CHImageView) convertView
.findViewById(R.id.list_night_picture);
String nightp = tweather.get(position).getNightPictureUrl();
list_night_picture.loadImage(nightp);
// 天气情况
TextView list_weather = (TextView) convertView
.findViewById(R.id.list_weather);
list_weather.setText(tweather.get(position).getWeather());
// 温度
TextView list_temperature = (TextView) convertView
.findViewById(R.id.list_temperature);
String str = tweather.get(position).getTemperature();
if(str.length() > 4){
//默认将最低温度显示在前面的算法
String str1 = str.substring(0, str.length()-1);
String str2 = str.substring(str.length()-1, str.length());
Log.i("TAG", str2);
String [] mstr = str1.split("~", 2);
list_temperature.setText(mstr[1]+" ~ "+mstr[0]+str2);
}else{
list_temperature.setText(str);
}
// 风力
TextView list_wind = (TextView) convertView
.findViewById(R.id.list_wind);
list_wind.setText(tweather.get(position).getWind());
return convertView;
}
/**
* 屏蔽item的点击事件
*/
@Override
public boolean isEnabled(int position) {
return false;
}
}
================================================
FILE: src/com/htq/coolweather/base/Appliction.java
================================================
package com.htq.coolweather.base;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextDirectionHeuristic;
import com.htq.coolweather.utils.SharePrefrenceUtil;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
public class Appliction extends Application{
@Override
public void onCreate() {
initImageLoader(this);
}
private void initImageLoader(Context ctx) {
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
ctx).threadPriority(Thread.NORM_PRIORITY - 2)
.denyCacheImageMultipleSizesInMemory()
.discCacheFileNameGenerator(new Md5FileNameGenerator())
.tasksProcessingOrder(QueueProcessingType.LIFO)
.discCacheSize(32 * 1024 * 1024)
.memoryCacheSize(4 * 1024 * 1024).enableLogging().build();
ImageLoader.getInstance().init(config);
}
public static boolean isNetWorkConnect(Context context)
{
ConnectivityManager connectivityManager=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
if(networkInfo==null||!networkInfo.isAvailable())
return false;
else {
return true;
}
}
}
================================================
FILE: src/com/htq/coolweather/base/AutoLocation.java
================================================
package com.htq.coolweather.base;
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;
public class AutoLocation extends Service implements LocationListener{
private LocationManager locationmanager;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
locationmanager = (LocationManager) getSystemService(LOCATION_SERVICE);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(locationmanager.getProvider(LocationManager.NETWORK_PROVIDER) != null){
locationmanager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}else if(locationmanager.getProvider(LocationManager.GPS_PROVIDER) != null){
locationmanager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}else{
Toast.makeText(this, "无法定位", Toast.LENGTH_SHORT).show();
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public boolean stopService(Intent name) {
return super.stopService(name);
}
@Override
public void onLocationChanged(Location location) {
//通知Activity
Intent intent = new Intent();
intent.setAction("locationAction");
intent.putExtra("location", location.toString());
sendBroadcast(intent);
//移除监听,停止服务
locationmanager.removeUpdates(this);
stopSelf();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
}
================================================
FILE: src/com/htq/coolweather/base/CHImageView.java
================================================
/**
* File:IVideoImageView.java
* Date:2013-12-2
*
* 四川长虹网络科技有限责任公司 (智能应用研发�?© 版权�?��
*/
package com.htq.coolweather.base;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.widget.ImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
/**
* 继承自ImageView,用于异步加载图片,在下载图片时使用设置的loading图片占位,图片下载好后刷新View
*
* @author 段文
*/
public class CHImageView extends ImageView {
/**
* 用于记录默认下载中状态的图片
*/
private int downLoadingImageId = 0;
private int downLoadingImagefailureId = 0;
// 图片是否加载成功
private boolean loadSuccess = false;
/**
* 不设置将使用默认图片 设置下载中,与加载失败的图片,
*
* @param downlding
* 加载�? * @param failureId 加载失败
*/
public void setDefultDownLoadAndFailureImage(int downlding, int failureId) {
downLoadingImageId = downlding;
downLoadingImagefailureId = failureId;
}
public CHImageView(Context context) {
super(context);
}
public CHImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CHImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/**
* 对外接口,用于调用ImageView的异步下载图片功�? *
*
* @param url
* 图片的URL
*/
public void loadImage(String url) {
DisplayImageOptions options = new DisplayImageOptions.Builder()
.showStubImage(downLoadingImageId)
.showImageForEmptyUri(downLoadingImagefailureId)
.cacheInMemory().cacheOnDisc()
.showImageOnFail(downLoadingImagefailureId)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
ImageLoader.getInstance().displayImage(url, this,options);
//
// ImageLoader.getInstance().loadImage(url, options,
// new ImageLoadingListener() {
//
// @Override
// public void onLoadingStarted(String arg0, View arg1) {
// loadSuccess = false;
// setImageResource(downLoadingImageId);
// }
//
// @Override
// public void onLoadingFailed(String arg0, View arg1,
// FailReason arg2) {
// loadSuccess = false;
// setImageResource(downLoadingImagefailureId);
// }
//
// @Override
// public void onLoadingComplete(String arg0, View arg1,
// Bitmap arg2) {
//
// if (getTag() == null || arg0.equals(getTag())) {
// loadSuccess = true;
// setImageBitmap(arg2);
// }
// }
//
// @Override
// public void onLoadingCancelled(String arg0, View arg1) {
// loadSuccess = false;
// setImageResource(downLoadingImagefailureId);
// }
// });
}
public boolean isLoadSuccess() {
return loadSuccess;
}
}
================================================
FILE: src/com/htq/coolweather/base/MHttpEntity.java
================================================
package com.htq.coolweather.base;
import java.io.IOException;
import java.net.SocketTimeoutException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import android.net.Uri;
import android.os.Message;
public class MHttpEntity {
private Message message;
private HttpEntity hentity;
public static final int succeed = 1;
public static final int fail = 2;
public static final int nonet = 3;
public Message getMessage() {
return message;
}
public void setMessage(Message message) {
this.message = message;
}
public HttpEntity getHentity() {
return hentity;
}
public void setHentity(HttpEntity hentity) {
this.hentity = hentity;
}
public static MHttpEntity sendhttpclient(String str) {
MHttpEntity mhe = new MHttpEntity();
Message Mesg = Message.obtain();
HttpEntity he = null;
HttpClient hClient = new DefaultHttpClient();// 实例化得到一个网络连接对象
HttpConnectionParams.setConnectionTimeout(hClient.getParams(), 5000);//连接超时设置
String mstr = Uri.decode(str);// 将String类型转为uri.有中文则必有此句。
HttpGet hget = new HttpGet(mstr);// 创建Http请求(get请求)
try {
HttpResponse re = hClient.execute(hget);// 执行一个请求
if (re.getStatusLine().getStatusCode() == 200) {
he = re.getEntity();// 获得数据实体
Mesg.arg1 = succeed;// 保存网络状态
} else {
Mesg.arg1 = fail;// 保存网络状态
}
} catch (SocketTimeoutException e) {
Mesg.arg1 = fail;
e.printStackTrace();
} catch (ClientProtocolException e) {
Mesg.arg1 = fail;
e.printStackTrace();
} catch (IOException e) {
Mesg.arg1 = fail;
e.printStackTrace();
}
mhe.setMessage(Mesg);
mhe.setHentity(he);
return mhe;
}
}
================================================
FILE: src/com/htq/coolweather/base/SQLiteCityManager.java
================================================
package com.htq.coolweather.base;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class SQLiteCityManager extends SQLiteOpenHelper{
public SQLiteCityManager(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "create table coolWeather(_id integer primary key autoincrement, cityname varchar(20), "
+ "imageurl varchar(20), weather varchar(20), temp varchar(20));";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists person;");
}
}
================================================
FILE: src/com/htq/coolweather/base/SendDataEntity.java
================================================
package com.htq.coolweather.base;
public class SendDataEntity {
public static String city = "";
public static String json = "json";
public static String ak = "iGs8rFvzh1e8c7C9DjXT5toK";
public static void setCity(String city) {
SendDataEntity.city = city;
}
public static void setJson(String json) {
SendDataEntity.json = json;
}
public static void setAk(String ak) {
SendDataEntity.ak = ak;
}
public static String getCity() {
return city;
}
public static String getJson() {
return json;
}
public static String getAk() {
return ak;
}
public static String getData() {
return "http://api.map.baidu.com/telematics/v3/weather?location=" +
city + "&output="+ json +"&ak="+ ak;
}
}
================================================
FILE: src/com/htq/coolweather/entity/BgPicEntity.java
================================================
package com.htq.coolweather.entity;
import android.graphics.Bitmap;
public class BgPicEntity {
public Bitmap bitmap;
public String path;
}
================================================
FILE: src/com/htq/coolweather/entity/CityManagerEntity.java
================================================
package com.htq.coolweather.entity;
public class CityManagerEntity {
private String city;//城市
private String weatherimage;//天气图片
private String temp;//温度
private String weather;//天气
private String dec;//描述
public String getWeather() {
return weather;
}
public void setWeather(String weather) {
this.weather = weather;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getWeatherimage() {
return weatherimage;
}
public void setWeatherimage(String weatherimage) {
this.weatherimage = weatherimage;
}
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
public String getDec() {
return dec;
}
public void setDec(String dec) {
this.dec = dec;
}
}
================================================
FILE: src/com/htq/coolweather/entity/LivingIndexEntity.java
================================================
package com.htq.coolweather.entity;
public class LivingIndexEntity {
private String title;//标题(穿衣,洗车,旅游,感冒 ,运动,紫外线强度)
private String suitable;//是否适宜
private String tipt;//各项指数名称
private String des;//简介
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getZs() {
return suitable;
}
public void setZs(String suitable) {
this.suitable = suitable;
}
public String getTipt() {
return tipt;
}
public void setTipt(String tipt) {
this.tipt = tipt;
}
public String getDes() {
return des;
}
public void setDes(String des) {
this.des = des;
}
}
================================================
FILE: src/com/htq/coolweather/entity/MHttpEntity.java
================================================
package com.htq.coolweather.entity;
import java.io.IOException;
import java.net.SocketTimeoutException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import android.net.Uri;
import android.os.Message;
import android.util.Log;
public class MHttpEntity {//之所以命名为MHttpEntity是因为在安卓中已存在HttpEntity
private Message message;
private HttpEntity hentity;
public static final int succeed = 1;
public static final int fail = 2;
public static final int nonet = 3;
public Message getMessage() {
return message;
}
public void setMessage(Message message) {
this.message = message;
}
public HttpEntity getHentity() {
return hentity;
}
public void setHentity(HttpEntity hentity) {
this.hentity = hentity;
}
public static MHttpEntity sendHttpRequest(String str) {
Log.i("TAG", System.currentTimeMillis()+"System.currentTimeMillis()333");
MHttpEntity mhe = new MHttpEntity();
Message Mesg = Message.obtain();
HttpEntity he = null;
HttpClient hClient = new DefaultHttpClient();// 实例化得到一个网络连接对象
HttpConnectionParams.setConnectionTimeout(hClient.getParams(), 5000);//连接超时设置
String mstr = Uri.decode(str);// 将String类型转为uri.有中文则必有此句。
HttpGet hget = new HttpGet(mstr);// 创建Http请求(get请求)
try {
HttpResponse re = hClient.execute(hget);// 执行一个请求
if (re.getStatusLine().getStatusCode() == 200) {
he = re.getEntity();// 获得数据实体
Mesg.arg1 = succeed;// 保存网络状态
} else {
Mesg.arg1 = fail;// 保存网络状态
}
} catch (SocketTimeoutException e) {
Mesg.arg1 = fail;
e.printStackTrace();
} catch (ClientProtocolException e) {
Mesg.arg1 = fail;
e.printStackTrace();
} catch (IOException e) {
Mesg.arg1 = fail;
e.printStackTrace();
}
mhe.setMessage(Mesg);
mhe.setHentity(he);
Log.i("TAG", mhe.getHentity() + " mhe.getHentity()");
return mhe;
}
}
================================================
FILE: src/com/htq/coolweather/entity/ResponseWrapper.java
================================================
package com.htq.coolweather.entity;
import java.util.List;
/**
*
* @author htq 爱丽颖的颖火虫
* bolg:www.csdn.net/htq__
*/
public class ResponseWrapper {
private int error;//错误次数
private String status;//返回结果状态信息
private String date;//当前时间
private List results;//天气预报信息
public int getError() {
return error;
}
public void setError(int error) {
this.error = error;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public List getResults() {
return results;
}
public void setResults(List results) {
this.results = results;
}
}
================================================
FILE: src/com/htq/coolweather/entity/SQLiteCityManager.java
================================================
package com.htq.coolweather.entity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class SQLiteCityManager extends SQLiteOpenHelper{
public SQLiteCityManager(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "create table coolWeather(_id integer primary key autoincrement, cityname varchar(20), "
+ "imageurl varchar(20), weather varchar(20), temp varchar(20));";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists person;");
}
}
================================================
FILE: src/com/htq/coolweather/entity/SendDataEntity.java
================================================
package com.htq.coolweather.entity;
/**
*
* @author htq
* blog:http://www.csdn.net/htq__
*/
public class SendDataEntity {//通过百度地图定位得到的城市名来获取该城市的天气信息的实体类
public static String city = "";
public static String json = "json";
public static String ak = "iGs8rFvzh1e8c7C9DjXT5toK";
public static void setCity(String city) {
SendDataEntity.city = city;
}
public static void setJson(String json) {
SendDataEntity.json = json;
}
public static void setAk(String ak) {
SendDataEntity.ak = ak;
}
public static String getCity() {
return city;
}
public static String getJson() {
return json;
}
public static String getAk() {
return ak;
}
public static String getData() {
return "http://api.map.baidu.com/telematics/v3/weather?location=" +
city + "&output="+ json +"&ak="+ ak;
}
//http://api.map.baidu.com/telematics/v3/weather?location=武汉&output=json&ak=iGs8rFvzh1e8c7C9DjXT5toK
}
================================================
FILE: src/com/htq/coolweather/entity/WeatherEntity.java
================================================
package com.htq.coolweather.entity;
import java.util.List;
/**
*
* @author htq
* bolg:www.csdn.net/htq__
*/
public class WeatherEntity {
private String currentCity;//当前城市
private List weather_data;//天气预报信息
private String pm25;//PM2.5值
private List index;//各项指数
public String getCurrentCity() {
return currentCity;
}
public void setCurrentCity(String currentCity) {
this.currentCity = currentCity;
}
public List getWeather_data() {
return weather_data;
}
public void setWeather_data(List weather_data) {
this.weather_data = weather_data;
}
public String getPm25() {
return pm25;
}
public void setPm25(String pm25) {
this.pm25 = pm25;
}
public List getIndex() {
return index;
}
public void setIndex(List index) {
this.index = index;
}
}
================================================
FILE: src/com/htq/coolweather/entity/WeatherSubEntity.java
================================================
package com.htq.coolweather.entity;
public class WeatherSubEntity {
private String date;//天气预报时间
private String dayPictureUrl;//白天的天气预报图片url
private String nightPictureUrl;//晚上的天气预报图片url
private String weather;//天气状况
private String wind;//风力
private String temperature;//温度
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDayPictureUrl() {
return dayPictureUrl;
}
public void setDayPictureUrl(String dayPictureUrl) {
this.dayPictureUrl = dayPictureUrl;
}
public String getNightPictureUrl() {
return nightPictureUrl;
}
public void setNightPictureUrl(String nightPictureUrl) {
this.nightPictureUrl = nightPictureUrl;
}
public String getWeather() {
return weather;
}
public void setWeather(String weather) {
this.weather = weather;
}
public String getWind() {
return wind;
}
public void setWind(String wind) {
this.wind = wind;
}
public String getTemperature() {
return temperature;
}
public void setTemperature(String temperature) {
this.temperature = temperature;
}
}
================================================
FILE: src/com/htq/coolweather/utils/CircleImageView.java
================================================
package com.htq.coolweather.utils;
import com.htq.coolweather.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.widget.ImageView;
public class CircleImageView extends ImageView {
private static final ScaleType SCALE_TYPE = ScaleType.CENTER_CROP;
private static final Bitmap.Config BITMAP_CONFIG = Bitmap.Config.ARGB_8888;
private static final int COLORDRAWABLE_DIMENSION = 2;
private static final int DEFAULT_BORDER_WIDTH = 0;
private static final int DEFAULT_BORDER_COLOR = Color.BLACK;
private static final int DEFAULT_FILL_COLOR = Color.TRANSPARENT;
private static final boolean DEFAULT_BORDER_OVERLAY = false;
private final RectF mDrawableRect = new RectF();
private final RectF mBorderRect = new RectF();
private final Matrix mShaderMatrix = new Matrix();
private final Paint mBitmapPaint = new Paint();
private final Paint mBorderPaint = new Paint();
private final Paint mFillPaint = new Paint();
private int mBorderColor = DEFAULT_BORDER_COLOR;
private int mBorderWidth = DEFAULT_BORDER_WIDTH;
private int mFillColor = DEFAULT_FILL_COLOR;
private Bitmap mBitmap;
private BitmapShader mBitmapShader;
private int mBitmapWidth;
private int mBitmapHeight;
private float mDrawableRadius;
private float mBorderRadius;
private ColorFilter mColorFilter;
private boolean mReady;
private boolean mSetupPending;
private boolean mBorderOverlay;
public CircleImageView(Context context) {
super(context);
init();
}
public CircleImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CircleImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleImageView, defStyle, 0);
mBorderWidth = a.getDimensionPixelSize(R.styleable.CircleImageView_civ_border_width, DEFAULT_BORDER_WIDTH);
mBorderColor = a.getColor(R.styleable.CircleImageView_civ_border_color, DEFAULT_BORDER_COLOR);
mBorderOverlay = a.getBoolean(R.styleable.CircleImageView_civ_border_overlay, DEFAULT_BORDER_OVERLAY);
mFillColor = a.getColor(R.styleable.CircleImageView_civ_fill_color, DEFAULT_FILL_COLOR);
a.recycle();
init();
}
private void init() {
super.setScaleType(SCALE_TYPE);
mReady = true;
if (mSetupPending) {
setup();
mSetupPending = false;
}
}
@Override
public ScaleType getScaleType() {
return SCALE_TYPE;
}
@Override
public void setScaleType(ScaleType scaleType) {
if (scaleType != SCALE_TYPE) {
throw new IllegalArgumentException(String.format("ScaleType %s not supported.", scaleType));
}
}
@Override
public void setAdjustViewBounds(boolean adjustViewBounds) {
if (adjustViewBounds) {
throw new IllegalArgumentException("adjustViewBounds not supported.");
}
}
@Override
protected void onDraw(Canvas canvas) {
if (mBitmap == null) {
return;
}
if (mFillColor != Color.TRANSPARENT) {
canvas.drawCircle(getWidth() / 2.0f, getHeight() / 2.0f, mDrawableRadius, mFillPaint);
}
canvas.drawCircle(getWidth() / 2.0f, getHeight() / 2.0f, mDrawableRadius, mBitmapPaint);
if (mBorderWidth != 0) {
canvas.drawCircle(getWidth() / 2.0f, getHeight() / 2.0f, mBorderRadius, mBorderPaint);
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
setup();
}
public int getBorderColor() {
return mBorderColor;
}
public void setBorderColor( int borderColor) {
if (borderColor == mBorderColor) {
return;
}
mBorderColor = borderColor;
mBorderPaint.setColor(mBorderColor);
invalidate();
}
public void setBorderColorResource( int borderColorRes) {
setBorderColor(getContext().getResources().getColor(borderColorRes));
}
public int getFillColor() {
return mFillColor;
}
public void setFillColor( int fillColor) {
if (fillColor == mFillColor) {
return;
}
mFillColor = fillColor;
mFillPaint.setColor(fillColor);
invalidate();
}
public void setFillColorResource( int fillColorRes) {
setFillColor(getContext().getResources().getColor(fillColorRes));
}
public int getBorderWidth() {
return mBorderWidth;
}
public void setBorderWidth(int borderWidth) {
if (borderWidth == mBorderWidth) {
return;
}
mBorderWidth = borderWidth;
setup();
}
public boolean isBorderOverlay() {
return mBorderOverlay;
}
public void setBorderOverlay(boolean borderOverlay) {
if (borderOverlay == mBorderOverlay) {
return;
}
mBorderOverlay = borderOverlay;
setup();
}
@Override
public void setImageBitmap(Bitmap bm) {
super.setImageBitmap(bm);
mBitmap = bm;
setup();
}
@Override
public void setImageDrawable(Drawable drawable) {
super.setImageDrawable(drawable);
mBitmap = getBitmapFromDrawable(drawable);
setup();
}
@Override
public void setImageResource( int resId) {
super.setImageResource(resId);
mBitmap = getBitmapFromDrawable(getDrawable());
setup();
}
@Override
public void setImageURI(Uri uri) {
super.setImageURI(uri);
mBitmap = uri != null ? getBitmapFromDrawable(getDrawable()) : null;
setup();
}
@Override
public void setColorFilter(ColorFilter cf) {
if (cf == mColorFilter) {
return;
}
mColorFilter = cf;
mBitmapPaint.setColorFilter(mColorFilter);
invalidate();
}
private Bitmap getBitmapFromDrawable(Drawable drawable) {
if (drawable == null) {
return null;
}
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
try {
Bitmap bitmap;
if (drawable instanceof ColorDrawable) {
bitmap = Bitmap.createBitmap(COLORDRAWABLE_DIMENSION, COLORDRAWABLE_DIMENSION, BITMAP_CONFIG);
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), BITMAP_CONFIG);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private void setup() {
if (!mReady) {
mSetupPending = true;
return;
}
if (getWidth() == 0 && getHeight() == 0) {
return;
}
if (mBitmap == null) {
invalidate();
return;
}
mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mBitmapPaint.setAntiAlias(true);
mBitmapPaint.setShader(mBitmapShader);
mBorderPaint.setStyle(Paint.Style.STROKE);
mBorderPaint.setAntiAlias(true);
mBorderPaint.setColor(mBorderColor);
mBorderPaint.setStrokeWidth(mBorderWidth);
mFillPaint.setStyle(Paint.Style.FILL);
mFillPaint.setAntiAlias(true);
mFillPaint.setColor(mFillColor);
mBitmapHeight = mBitmap.getHeight();
mBitmapWidth = mBitmap.getWidth();
mBorderRect.set(0, 0, getWidth(), getHeight());
mBorderRadius = Math.min((mBorderRect.height() - mBorderWidth) / 2.0f, (mBorderRect.width() - mBorderWidth) / 2.0f);
mDrawableRect.set(mBorderRect);
if (!mBorderOverlay) {
mDrawableRect.inset(mBorderWidth, mBorderWidth);
}
mDrawableRadius = Math.min(mDrawableRect.height() / 2.0f, mDrawableRect.width() / 2.0f);
updateShaderMatrix();
invalidate();
}
private void updateShaderMatrix() {
float scale;
float dx = 0;
float dy = 0;
mShaderMatrix.set(null);
if (mBitmapWidth * mDrawableRect.height() > mDrawableRect.width() * mBitmapHeight) {
scale = mDrawableRect.height() / (float) mBitmapHeight;
dx = (mDrawableRect.width() - mBitmapWidth * scale) * 0.5f;
} else {
scale = mDrawableRect.width() / (float) mBitmapWidth;
dy = (mDrawableRect.height() - mBitmapHeight * scale) * 0.5f;
}
mShaderMatrix.setScale(scale, scale);
mShaderMatrix.postTranslate((int) (dx + 0.5f) + mDrawableRect.left, (int) (dy + 0.5f) + mDrawableRect.top);
mBitmapShader.setLocalMatrix(mShaderMatrix);
}
}
================================================
FILE: src/com/htq/coolweather/utils/SharePrefrenceUtil.java
================================================
package com.htq.coolweather.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
public class SharePrefrenceUtil {
private static final String BG_PIC_PATH ="bg_pic_path";
private SharedPreferences mSp;
private Editor mEditor;
public SharePrefrenceUtil(Context context) {
mSp = context.getSharedPreferences("coolWeather",
Context.MODE_WORLD_WRITEABLE);
mEditor = mSp.edit();
}
/**
* 保存背景皮肤图片的地址
* @author: htq
*/
public void saveBgPicPath(String path)
{
mEditor.putString(BG_PIC_PATH, path);
mEditor.commit();
}
/**
* 获取背景皮肤图片的地址
*/
public String getPath() {
return mSp.getString(BG_PIC_PATH, null);
}
}
================================================
FILE: src/com/htq/coolweather/utils/SystemUtils.java
================================================
package com.htq.coolweather.utils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
public class SystemUtils {
/**
* @author htq_
* @param mActivity
* bolg:www.csdn.net/htq__
*/
public static void shareApp(Activity mActivity)
{
String shareAppContent="各位亲爱的小伙伴们,我发现了一款简约好用且颜值爆表的天气APP酷我天气,分享给大家,记得关注作者的博客http://blog.csdn.net/htq__,福利多多哦!";
new File(mActivity.getFilesDir(), "share.png").deleteOnExit();
FileOutputStream fileOutputStream=null;
try {
fileOutputStream = mActivity.openFileOutput(
"share.png", 1);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap pic=BitmapFactory.decodeResource(mActivity.getResources(),com.htq.coolweather.R.drawable.cool_weather_icon);
pic.compress(CompressFormat.JPEG, 100,fileOutputStream);
Intent intent = new Intent("android.intent.action.SEND");
intent.setType("image/*");
intent.putExtra("sms_body", shareAppContent);
intent.putExtra("android.intent.extra.TEXT",shareAppContent);
intent.putExtra("android.intent.extra.STREAM",
Uri.fromFile(new File(mActivity.getFilesDir(), "share.png")));
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mActivity.startActivity(Intent.createChooser(intent,"好东西要与小伙伴们一起分享"));
}
}