代码只是随意写写,有些地方有些冗余,且观赏度不高,发表只为记录一下。
主体界面的布局代码,其余布局代码会单独出一篇
传送门:布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinerLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainPage"
android:orientation="vertical">
<androidx.viewpager.widget.ViewPager
android:id="@+id/vpager_four"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_weight="1.0"
android:flipInterval="30"
android:persistentDrawingCache="animation" />
<ImageView
android:id="@+id/img_cursor"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scaleType="matrix"
android:src="@mipmap/line" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="48dp"
android:background="#ffffff">
<TextView
android:id="@+id/main_one"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1.0"
android:gravity="center"
android:text="天气"
android:textColor="#000000" />
<TextView
android:id="@+id/main_two"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1.0"
android:gravity="center"
android:text="天气备忘录"
android:textColor="#000000" />
<TextView
android:id="@+id/main_three"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1.0"
android:gravity="center"
android:text="发现"
android:textColor="#000000" />
<TextView
android:id="@+id/main_four"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1.0"
android:gravity="center"
android:text="个人信息"
android:textColor="#000000" />
</LinearLayout>
</LinearLayout>
主体界面代码,确保了app的主体框架,实现天气查询功能,及中国天气官网查看功能。
package com.example.theapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.example.theapp.DataBase.Dao;
import com.example.theapp.ToolClass.ListItem;
import com.example.theapp.ToolClass.MyPagerAdapter;
import com.example.theapp.ToolClass.StreamTool;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class MainPage extends AppCompatActivity
implements ViewPager.OnPageChangeListener, View.OnClickListener {
//整体框架控件
private ViewPager vpager_four;
private ImageView img_cursor;
private TextView main_one,main_two,main_three,main_four;
//个人信息控件
private Button nicheng;
private Button zhuxiao;
private Button code;
private ImageButton image;
private TextView name;
private int flag;
//天气界面控件
private EditText cityname;
private TextView search_city,weather,temp,aqi,cloud;
private Button search;
private ListView listV;
private LinearLayout linearLayout;
final String[] con = new String[11];
//天气备忘录界面控件
private EditText add_city;
private Button add;
private ListView list_view;
private List<ListItem> itemList=new ArrayList<>();
private String[] content=new String[11];
//工具界面控件
private Button joke,history;
private ArrayList<View> listViews;
private int offset = 0;//移动条图片的偏移量
private int currIndex = 0;//当前页面的编号
private int bmpWidth;// 移动条图片的长度
private int one = 0; //移动条滑动一页的距离
private int two = 0; //滑动条移动两页的距离
private int three = 0; //滑动条移动两页的距离
@SuppressLint("HandlerLeak")
private Handler handler=new Handler(){
public void handleMessage(android.os.Message message){
JSONObject jsonObject= (JSONObject) message.obj;
try {
con[0] = jsonObject.getString("reason");
JSONObject result = jsonObject.getJSONObject("result");
con[1] = result.getString("city");
JSONObject realtime = result.getJSONObject("realtime");
con[2] = realtime.getString("info") ;
String regx1=".*雨.*";
String regx2=".*晴.*";
String regx3=".*阴.*";
String regx4=".*雪.*";
if( con[2].matches(regx1)){
linearLayout.setBackgroundResource(R.drawable.rain);
}else if(con[2].matches(regx2)){
linearLayout.setBackgroundResource(R.drawable.sun);
}else if(con[2].matches(regx3)){
linearLayout.setBackgroundResource(R.drawable.cloudy);
}else if(con[2].matches(regx4)){
linearLayout.setBackgroundResource(R.drawable.snow);
}else
{
linearLayout.setBackgroundResource(R.drawable.back);
}
con[3] = realtime.getString("temperature");
con[4] ="空气质量:"+ realtime.getString("aqi");
con[5] ="风力:"+ realtime.getString("direct") + " 等级:" + realtime.getString("power");
JSONArray array=result.getJSONArray("future");
JSONObject jsonObject1=array.getJSONObject(1);
JSONObject jsonObject2=array.getJSONObject(2);
JSONObject jsonObject3=array.getJSONObject(3);
JSONObject jsonObject4=array.getJSONObject(4);
con[6]="日期:"+jsonObject1.getString("date")+" 最低/最高温度:"+jsonObject1.getString("temperature")
+" 天气情况:"+jsonObject1.getString("weather")+" 风力:等级:"+jsonObject1.getString("direct");
con[7]="日期:"+jsonObject2.getString("date")+" 最低/最高温度:"+jsonObject2.getString("temperature")
+" 天气情况:"+jsonObject2.getString("weather")+" 风力:等级:"+jsonObject2.getString("direct");
con[8]="日期:"+jsonObject3.getString("date")+" 最低/最高温度:"+jsonObject3.getString("temperature")
+" 天气情况:"+jsonObject3.getString("weather")+" 风力:等级:"+jsonObject3.getString("direct");
con[9]="日期:"+jsonObject4.getString("date")+" 最低/最高温度:"+jsonObject4.getString("temperature")
+" 天气情况:"+jsonObject4.getString("weather")+" 风力:等级:"+jsonObject4.getString("direct");
search_city.setText(con[1]);
weather.setText(con[2]);
temp.setText(con[3]);
aqi.setText(con[4]);
cloud.setText(con[5]);
listV.setAdapter(new BaseAdapter() {
@Override
public int getCount() {
return 5;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView textView=new TextView(MainPage.this);
textView.setTextSize(20);
textView.setTextColor(Color.parseColor("#FF0D29"));
textView.setText(con[position+6]);
return textView;
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
init();
}
public void init(){
//主体界面初始化
vpager_four =findViewById(R.id.vpager_four);
main_one =findViewById(R.id.main_one);
main_two = findViewById(R.id.main_two);
main_three = findViewById(R.id.main_three);
main_four =findViewById(R.id.main_four);
img_cursor =findViewById(R.id.img_cursor);
//下划线动画的相关设置:
bmpWidth = BitmapFactory.decodeResource(getResources(), R.mipmap.line).getWidth();// 获取图片宽度
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int screenW = dm.widthPixels;// 获取分辨率宽度
offset = (screenW / 4 - bmpWidth) / 2;// 计算偏移量
Matrix matrix = new Matrix();
matrix.postTranslate(offset, 0);
img_cursor.setImageMatrix(matrix);// 设置动画初始位置
//移动的距离
one = offset * 2 + bmpWidth;// 移动一页的偏移量,比如1->2,或者2->3
two = one * 2;// 移动两页的偏移量,比如1直接跳3
three=one*3;
//往ViewPager填充View,同时设置点击事件与页面切换事件
listViews = new ArrayList<View>();
LayoutInflater mInflater = getLayoutInflater();
listViews.add(mInflater.inflate(R.layout.view_weather, null, false));
listViews.add(mInflater.inflate(R.layout.view_two, null, false));
listViews.add(mInflater.inflate(R.layout.view_find, null, false));
listViews.add(mInflater.inflate(R.layout.view_personalmessage, null, false));
vpager_four.setAdapter(new MyPagerAdapter(listViews));
vpager_four.setCurrentItem(0); //设置ViewPager当前页,从0开始算
//四个页面的点击事件
main_one.setOnClickListener(this);
main_two.setOnClickListener(this);
main_three.setOnClickListener(this);
main_four.setOnClickListener(this);
vpager_four.addOnPageChangeListener( this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
//天气查询界面
case R.id.main_one:
vpager_four.setCurrentItem(0);
cityname=findViewById(R.id.city_name);
search_city=findViewById(R.id.search_city);
weather=findViewById(R.id.weather);
temp=findViewById(R.id.temp);
aqi=findViewById(R.id.aqi);
cloud=findViewById(R.id.cloud);
search=findViewById(R.id.search);
listV=findViewById(R.id.lv);
linearLayout=findViewById(R.id.LinerLayout_weather);
search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String cn = cityname.getText().toString().trim();
if (TextUtils.isEmpty(cn)) {
Toast.makeText(MainPage.this, "请输入正确的城市名称!", Toast.LENGTH_SHORT).show();
linearLayout.setBackgroundResource(R.drawable.back);
return;
}else{
final String city_name = cityname.getText().toString();
getData(city_name);
linearLayout.invalidate();
}
}
});
listV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final AlertDialog.Builder builder=new Builder(MainPage.this);
builder.setIcon(R.drawable.icon);
builder.setTitle("请选择你要打开的方式");
final String[] items=new String[]{"使用浏览器打开中国天气官网","本应用打开中国天气官网"};
builder.setSingleChoiceItems(items, -1, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(which==0){
Intent intent=new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.weather.com.cn"));
startActivity(intent);
}else {
Intent intent=new Intent(MainPage.this,Weather_web.class);
startActivity(intent);
}
dialog.dismiss();
}
});
builder.show();
}
});
break;
//天气备忘录界面
case R.id.main_two:
vpager_four.setCurrentItem(1);
add_city=findViewById(R.id.add_city);
add=findViewById(R.id.add);
list_view=findViewById(R.id.list_view);
final Intent intent4=getIntent();
Bundle b1=intent4.getExtras();
final int[] fla = {1};
fla[0]=1;
final String u_name=b1.getString("name");
final Dao dao=new Dao(MainPage.this);
final Cursor cursor=dao.queryall(u_name);
String[] from={"cityname"};
int[] to={R.id.cityname};
SimpleCursorAdapter adapter=new SimpleCursorAdapter(MainPage.this,R.layout.display,cursor,from,to);
list_view.setAdapter(adapter);
list_view.invalidate();
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String cn = add_city.getText().toString().trim();
if (TextUtils.isEmpty(cn)) {
Toast.makeText(MainPage.this, "请输入正确的城市名称!", Toast.LENGTH_SHORT).show();
}else {
final Cursor cursor2=dao.queryall(u_name);
String[] from2={"cityname"};
int[] to2={R.id.cityname};
SimpleCursorAdapter adapter2=new SimpleCursorAdapter(MainPage.this,R.layout.display,cursor,from2,to2);
list_view.setAdapter(adapter2);
while(cursor2.moveToNext()){
String c_n=cursor2.getString(2);
if(add_city.getText().toString().equals(c_n)){
Toast.makeText(MainPage.this, "该城市已经存在!", Toast.LENGTH_SHORT).show();
fla[0] =0;
break;
}
}
if(fla[0]==1){
dao.insert(u_name,add_city.getText().toString());
final Cursor cursor1=dao.queryall(u_name);
String[] from1={"cityname"};
int[] to1={R.id.cityname};
SimpleCursorAdapter adapter1=new SimpleCursorAdapter(MainPage.this,R.layout.display,cursor1,from1,to1);
list_view.setAdapter(adapter1);
list_view.invalidate();
}
}
list_view.invalidate();
}
});
list_view.invalidate();
list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, final int position, final long id) {
new Thread() {
public void run() {
String city_name = dao.query_cityname(String.valueOf(id));
String path = null;
try {
path = "http://apis.juhe.cn/simpleWeather/query?city="
+ city_name + "&key=133be2a97bcc0a48b4bacb57e34a9ec8";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
int code = conn.getResponseCode();
if(code==200) {
InputStream is = conn.getInputStream();
String json = StreamTool.readStream(is);
JSONObject jsonObject = new JSONObject(json);
String reason=jsonObject.getString("reason");
Log.d("reason=",reason);
if("查询成功!".equals(reason)){
JSONObject result = jsonObject.getJSONObject("result");
content[1] = result.getString("city");
JSONObject realtime = result.getJSONObject("realtime");
content[2] = realtime.getString("info") ;
content[3] = realtime.getString("temperature");
content[4] ="空气质量:"+ realtime.getString("aqi");
content[5] ="风力:"+ realtime.getString("direct") + " 等级:" + realtime.getString("power");
JSONArray array=result.getJSONArray("future");
JSONObject jsonObject1=array.getJSONObject(1);
JSONObject jsonObject2=array.getJSONObject(2);
JSONObject jsonObject3=array.getJSONObject(3);
JSONObject jsonObject4=array.getJSONObject(4);
content[6]="日期:"+jsonObject1.getString("date")+" 最低/最高温度:"+jsonObject1.getString("temperature")
+" 天气情况:"+jsonObject1.getString("weather")+" 风力:等级:"+jsonObject1.getString("direct");
content[7]="日期:"+jsonObject2.getString("date")+" 最低/最高温度:"+jsonObject2.getString("temperature")
+" 天气情况:"+jsonObject2.getString("weather")+" 风力:等级:"+jsonObject2.getString("direct");
content[8]="日期:"+jsonObject3.getString("date")+" 最低/最高温度:"+jsonObject3.getString("temperature")
+" 天气情况:"+jsonObject3.getString("weather")+" 风力:等级:"+jsonObject3.getString("direct");
content[9]="日期:"+jsonObject4.getString("date")+" 最低/最高温度:"+jsonObject4.getString("temperature")
+" 天气情况:"+jsonObject4.getString("weather")+" 风力:等级:"+jsonObject4.getString("direct");
Intent intent3=new Intent(MainPage.this,WeatherNotes.class);
intent3.putExtra("city",content[1]);
intent3.putExtra("info",content[2]);
intent3.putExtra("temperature",content[3]);
intent3.putExtra("aqi",content[4]);
intent3.putExtra("cloudy",content[5]);
intent3.putExtra("f1",content[6]);
intent3.putExtra("f2",content[7]);
intent3.putExtra("f3",content[8]);
intent3.putExtra("f4",content[9]);
startActivity(intent3);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
});
final AlertDialog.Builder builder=new AlertDialog.Builder(this);
list_view.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
final long temp=id;
builder.setMessage("是否删除记录?").setPositiveButton("是", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dao.del((int) temp);
Cursor c=dao.queryall(u_name);
String[] from={"cityname"};
int[] to={R.id.cityname};
SimpleCursorAdapter adapter=new SimpleCursorAdapter(MainPage.this,R.layout.display,c,from,to);
list_view.setAdapter(adapter);
list_view.invalidate();
}
}).setNegativeButton("否", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog ad=builder.create();
ad.show();
return true;
}
});
break;
//发现小功能界面
case R.id.main_three:
vpager_four.setCurrentItem(2);
joke=findViewById(R.id.joke);
history=findViewById(R.id.history);
joke.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(MainPage.this,TheFunnyDay.class);
startActivity(intent);
}
});
history.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent1=new Intent(MainPage.this,TheHistory.class);
startActivity(intent1);
}
});
break;
//个人信息界面
case R.id.main_four:
//初始化个人信息界面
vpager_four.setCurrentItem(3);
name=findViewById(R.id.name);
code=findViewById(R.id.pass);
zhuxiao=findViewById(R.id.zhuxiao);
nicheng=findViewById(R.id.nicheng);
final Intent intent=getIntent();
Bundle b=intent.getExtras();
final String username=b.getString("name");
String password=b.getString("password");
final String nc=b.getString("nicheng");
name.setText(username);
code.setText(password);
nicheng.setText(nc);
//跳转到修改信息界面
code.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
flag=1;
Intent intent2=getIntent();
Bundle b1=intent2.getExtras();
String pass=b1.getString("password");
String name=b1.getString("name");
b1.putString("ecp",pass);
b1.putString("ecn",name);
b1.putString("flag", String.valueOf(flag));
Intent intent1=new Intent(MainPage.this,ChangeMessage.class);
intent1.putExtra("ecp",pass);
intent1.putExtra("ecn",name);
intent1.putExtra("flag",String.valueOf(flag));
startActivity(intent1);
}
});
zhuxiao.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent in=new Intent(MainPage.this,MainActivity.class);
startActivity(in);
}
});
nicheng.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
flag=2;
Intent intent3=getIntent();
Bundle b2=intent3.getExtras();
String NC=b2.getString("nicheng");
b2.putString("flag", String.valueOf(flag));
b2.putString("ecnc",NC);
Intent intent_nc=new Intent(MainPage.this,ChangeMessage.class);
intent_nc.putExtra("flag",String.valueOf(flag));
intent_nc.putExtra("ecnc",nc);
intent_nc.putExtra("ecn", username);
startActivityForResult(intent_nc,1);
}
});
break;
}
}
public void getData(final String city_name){
new Thread() {
public void run() {
String path = null;
try {
path = "http://apis.juhe.cn/simpleWeather/query?city="
+ city_name + "&key=133be2a97bcc0a48b4bacb57e34a9ec8";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
int code = conn.getResponseCode();
if(code==200) {
InputStream is = conn.getInputStream();
String json = StreamTool.readStream(is);
JSONObject jsonObject = new JSONObject(json);
String reason=jsonObject.getString("reason");
if("查询成功!".equals(reason)){
Message message=new Message();
message.obj=jsonObject;
handler.sendMessage(message);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
@Override
public void onActivityResult(int requestCode,int resultCode,Intent data) {
nicheng.setText(data.getStringExtra("data_return"));
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onPageSelected(int index) {
Animation animation = null;
switch (index) {
case 0:
if (currIndex == 1) {
animation = new TranslateAnimation(one, 0, 0, 0);
} else if (currIndex == 2) {
animation = new TranslateAnimation(two, 0, 0, 0);
}else if (currIndex == 3) {
animation = new TranslateAnimation(three, 0, 0, 0);
}
break;
case 1:
if (currIndex == 0) {
animation = new TranslateAnimation(offset, one, 0, 0);
} else if (currIndex == 2) {
animation = new TranslateAnimation(two, one, 0, 0);
}else if (currIndex == 3) {
animation = new TranslateAnimation(three, one, 0, 0);
}
break;
case 2:
if (currIndex == 0) {
animation = new TranslateAnimation(offset, two, 0, 0);
} else if (currIndex == 1) {
animation = new TranslateAnimation(one, two, 0, 0);
}else if (currIndex == 3) {
animation = new TranslateAnimation(three, two, 0, 0);
}
break;
case 3:
if (currIndex == 1) {
animation = new TranslateAnimation(offset, three, 0, 0);
} else if (currIndex == 2) {
animation = new TranslateAnimation(one, three, 0, 0);
}else if (currIndex == 0) {
animation = new TranslateAnimation(offset, three, 0, 0);
}
break;
}
currIndex = index;
animation.setFillAfter(true);// true表示图片停在动画结束位置
animation.setDuration(300); //设置动画时间为300毫秒
img_cursor.startAnimation(animation);//开始动画
}
@Override
public void onPageScrollStateChanged(int i) {
}
//position 当前所在页面 i
//positionOffset 当前所在页面偏移百分比 v
//positionOffsetPixels 当前所在页面偏移量 i1
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// View view=new View(MainPage.this);
// switch (position){
// case 0:
// onClick(view.findViewById(R.id.main_one));
// break;
// case 1:
// onClick(view.findViewById(R.id.main_two));
// break;
// case 2:
// onClick(view.findViewById(R.id.main_three));
// break;
// case 3:
// onClick(view.findViewById(R.id.main_four));
// break;
// }
}
@Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
}
传送门:app实现后详细情况