2016-06-04 13:52:23 hester_hester 阅读数 530

目标效果:

点击按钮,即可返回数据,在TextView和logcat中显示获取到的天气数据。


1.首先在聚合数据中注册账号:https://www.juhe.cn/login


2.进入我的数据后,点击申请数据,免费为500次。


3.申请后会在我的数据显示当前数据的信息,包括Appkey和剩余次数。


4.点击测试。


5.输入想要查询的城市名称,点击发送请求。


6.请求后会在请求详情里显示网址以及下方显示获取到的数据,网址格式为“http://v.juhe.cn/weather/index?format=2&cityname=%E8%8B%8F%E5%B7%9E&key=您申请的KEY”,其中%E8%8B%8F%E5%B7%9E部分为城市名称,该网址示例为苏州地区的天气,当在浏览器中可直接输入中文,但是程序中不可以,需要将中文转换为字符编码在进行访问。


7.开始编写代码,activity_main.xml页面放置需要的Button和TextView控件。

activity_main.xml页面:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <Button
        android:id="@+id/send_request"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send Request" />
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
        <TextView
            android:id="@+id/response"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>
</LinearLayout>


8.MainActivity.java页面进行数据的获取和显示。
MainActivity.java页面:
package com.example.networktest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
	private Button sendRequest;
	private TextView responseText;
	public static final int SHOW_RESPONSE = 0;
	private Handler handler = new Handler() {

		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SHOW_RESPONSE:
				String response = (String) msg.obj;
				// 在这里进行UI操作,将结果显示到界面上
				responseText.setText(response);
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		sendRequest = (Button) findViewById(R.id.send_request);
		responseText = (TextView) findViewById(R.id.response);
		sendRequest.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				/*获取天气数据*/
				sendRequestWithHttpURLConnection();
			}
		});
	}

	/**
	 * 获取天气数据
	 */
	protected void sendRequestWithHttpURLConnection() {
		new Thread() {     //创建线程
			@Override
			public void run() {
				URL url;
				HttpURLConnection connection = null;
				try {
					String cityName = URLEncoder.encode("滨州", "utf-8");   //将汉字转换为编码
					url = new URL(
							"http://v.juhe.cn/weather/index?format=2&cityname="+cityName+"&key=你自己的key"); 
					Log.i("MainActivity","url"+url);//设置访问地址
					connection = (HttpURLConnection) url.openConnection();     //实例化connection对象
					connection.setRequestMethod("GET");
					connection.setConnectTimeout(8000);
					connection.setReadTimeout(8000);
					InputStream in = connection.getInputStream();     //获取输入流
					// 下面对获取到的输入流进行读取
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(in));
					StringBuilder response = new StringBuilder();
					String line;
					while ((line = reader.readLine()) != null) {
						response.append(line);
					}
					Log.i("MainActivity","response=" + response.toString());
					parseWeatherWithJSON(response.toString());
					Message message = new Message();
					message.what = SHOW_RESPONSE;
					// 将服务器返回的结果存放到Message中
					message.obj = response.toString();
					handler.sendMessage(message);
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					if (connection != null) {
						connection.disconnect();
					}
				}
			}
		}.start();
	}

	protected void parseWeatherWithJSON(String response) {
		try {
			JSONObject jsonObject=new JSONObject(response);
			String resultcode=jsonObject.getString("resultcode");
			if(resultcode.equals("200")){
				JSONObject resultObject=jsonObject.getJSONObject("result");
				JSONObject todayObject=resultObject.getJSONObject("today");
				String date_y=todayObject.getString("date_y");
				String week=todayObject.getString("week");
				String temperature=todayObject.getString("temperature");
				Log.d("MainActivity", "date_y="+date_y+"week="+week+"temp="+temperature);
			}
			
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	protected void parseWithJSON(String response) {
		try {
			JSONArray jsonArray = new JSONArray(response);
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				String id = jsonObject.getString("id");
				String name = jsonObject.getString("name");
				String version = jsonObject.getString("version");
				Log.d("MainActivity", "id=" + id + "name=" + name + "version="
						+ version);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

}


9.添加权限
<uses-permission android:name="android.permission.INTERNET"/>


9.运行程序就可以显示获取到的天气数据了。









2016-06-02 13:30:46 zhupengqq 阅读数 8259

Android项目之天气预报 的实现分析


输入要查询的城市名称,点击查询按钮后,依次出现七天的天气情况。出现时有动画效果
二、实现过程
(一)获取天气预报数据
1、首先搞定天气预报数据来源的问题,提高天气预报服务的有很多网站,这些网站一般都会提供比较详细的 API 接口供应用程序调用,以聚合数据为例,其官网为:https://www.juhe.cn/如下图所示:


点击注册,进入注册界面:

登录成功后,就会进入到如下界面。


点击左侧菜单中我的数据,进入如下界面

点击申请新数据,如下所示,必须实名认证




进入聚合数据首页,选择 API 选项卡,选择免费的天气预报 API

点击进入后,只要申请就送 500 次使用,如下图所示。

复制其中的 AppKey:ab9d7e2007472d723baf71fcdc4ba094

打开全国天气预报 API 后,会有一项请求示例,按照其规则拼接字符串后在地址栏中输入
后可得



具体参照聚合数据的文档


下面是类的展示


2、编写网络数据访问工具类
首先需要在 uiti 包下定义一个接口,比如将它命名成 HttpCallbackListener,代码如下
package com.example.weather.util;

public interface HttpCallbackListener {
	void onFinish(String response);
	void onError(Exception e);
}
然后定义 HttpUtil 类,代码如下
package com.example.weather.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.util.Log;

public class HttpUtil {
	public static void sendHttpRequest(final String address, final HttpCallbackListener listener) {
		new Thread(new Runnable() {
			public void run() {
				HttpURLConnection connection = null;
				try {
					URL url = new URL(address);
					connection = (HttpURLConnection) url.openConnection();
					connection.setRequestMethod("GET");
					connection.setConnectTimeout(8000);
					connection.setReadTimeout(8000);
					connection.setDoInput(true);
					connection.setDoOutput(true);
					InputStream in = connection.getInputStream();
					BufferedReader reader =
							new BufferedReader(new InputStreamReader(in));
					StringBuilder response = new StringBuilder();
					String line;
					while ((line = reader.readLine()) != null) {
						response.append(line);		
					}
					if (listener != null) {
						// 回调 onFinish()方法
						listener.onFinish(response.toString());
					}
				} catch (Exception e) {
					if (listener != null) {
						// 回调 onError()方法
						listener.onError(e);
					}
				} finally {
					if (connection != null) {
						connection.disconnect();
					}
				}
			}
		}).start();
	}
}
3、测试一下能否正常访问天气预报接口得到返回的数据
package com.example.weather.test;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import com.example.weather.util.HttpCallbackListener;
import com.example.weather.util.HttpUtil;

import android.test.AndroidTestCase;

public class WeatherGetTest  extends AndroidTestCase{
	 public void testGetData(){	 
		 String cityName;
		try {
			cityName = URLEncoder.encode("菏泽", "utf-8");
			String  weatherUrl="http://v.juhe.cn/weather/index?format=2&cityname="+cityName+"&key=ab9d7e2007472d723baf71fcdc4ba094";
		
		 HttpUtil.sendHttpRequest(weatherUrl, new HttpCallbackListener() {
			
			public void onFinish(String response) {
				// TODO Auto-generated method stub
				System.out.println(response);
			}
			
			public void onError(Exception e) {
				// TODO Auto-generated method stub
				
			}
			});
		 }catch (Exception e) {
			// TODO: handle exception
		}
	
	 }
}

由于涉及到访问网络,需要在 AndroidManifest.xml 文件中加入访问网络的权限。
<uses-permission android:name="android.permisson.Internet"/>


(三)UI 设计
activity_weather.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/city"
    tools:context=".WeatherActivity" >

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

        <EditText
            android:id="@+id/etCity"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="20dp"
            android:layout_weight="1"
            android:background="@android:drawable/edit_text"
            android:drawableLeft="@drawable/etcity"
            android:drawablePadding="5dp"
            android:ems="10"
            android:hint="@string/etCity" >

            <requestFocus />
        </EditText>

        <ImageButton
            android:id="@+id/btnQuery"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_marginTop="20dp"      
            android:background="@null"
            android:src="@drawable/serch" />
    </LinearLayout>

    <ListView
        android:id="@+id/lvFutureWeather"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/linearLayout1"
        android:layout_centerHorizontal="true"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:dividerHeight="10dp"
        android:layoutAnimation="@anim/weather_list_layout_animation" >
    </ListView>

<span style="color:#ff0000;"></RelativeLayout></span>
activity_weather_listitem.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:background="@drawable/list_item_shape"
    android:padding="10dp" >

    <TextView
        android:id="@+id/tvDayofWeek"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="15dp"
        android:text="星期日" />

    <TextView
        android:id="@+id/tvDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/tvDayofWeek"
        android:layout_alignBottom="@+id/tvDayofWeek"
        android:layout_alignParentRight="true"
        android:text="20160207" />

    <TextView
        android:id="@+id/tvTemperature"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/tvDayofWeek"
        android:layout_below="@+id/tvDayofWeek"
        android:layout_marginTop="15dp"
        android:text="temperature" />

    <TextView
        android:id="@+id/tvWeather"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/tvTemperature"
        android:layout_below="@+id/tvTemperature"
        android:layout_marginTop="15dp"
        android:text="weather" />

</RelativeLayout>

其中 weather_list_layout_animation.xml 文件是一个设置布局动画的,实现过程如下 :
在 res 目录下新建 anim 文件夹, 在其下新建 weather_list_layout_animation.xml 文件, 如下:
weather_list_animation.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

    <scale
        android:duration="1000"
        android:fromXScale="0.0"
        android:fromYScale="0.0"
        android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:toXScale="1.0"
        android:toYScale="1.0" />

</set>
weather_list_layout_animation.xml
<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?>
<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
    android:animation="@anim/weather_list_animation"
    android:animationOrder="normal"
    android:delay="2" /></span>

Weather.java
package com.example.weather.moder;

public class Weather {
	private String dayOfWeek;//星期几
	private String date;//日期
	private String temperature;//温度
	private String weather;//天气
	public Weather(){
	}
	public Weather(String dayOfWeek, String date, String temperature,
			String weather) {
		super();
		this.dayOfWeek = dayOfWeek;
		this.date = date;
		this.temperature = temperature;
		this.weather = weather;
	}
	public String getDayOfWeek() {
		return dayOfWeek;
	}
	public void setDayOfWeek(String dayOfWeek) {
		this.dayOfWeek = dayOfWeek;
	}
	public String getDate() {
		return date;
	}
	public void setDate(String date) {
		this.date = date;
	}
	public String getTemperature() {
		return temperature;
	}
	public void setTemperature(String temperature) {
		this.temperature = temperature;
	}
	public String getWeather() {
		return weather;
	}
	public void setWeather(String weather) {
		this.weather = weather;
	}
	@Override
	public String toString() {
		return "Weather [dayOfWeek=" + dayOfWeek + ", date=" + date
				+ ", temperature=" + temperature + ", weather=" + weather + "]";
	}

}
在 adapter 包下定义适配器 WeatherAdapter
package com.example.weather.adapter;


import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.example.weather.R;
import com.example.weather.moder.Weather;

/**
 * 天气适配器
 * @author zhupeng
 *
 */
public class WeatherAdapter extends ArrayAdapter<Weather> {
	private int resourceId;
	public WeatherAdapter(Context context, int textViewResourceId,
			List<Weather> objects) {
		super(context, textViewResourceId, objects);
		resourceId = textViewResourceId;
	}
	@Override
	public View getView(int position, View convertView, ViewGroup viewgroup) {
		Weather weather=getItem(position);
		ViewHolder viewHolder=null;
		if(convertView==null){
			viewHolder=new ViewHolder();
			convertView=LayoutInflater.from(getContext()).inflate(resourceId, null);
			viewHolder.tvDayOfWeek=(TextView)
					convertView.findViewById(R.id.tvDayofWeek);
			viewHolder.tvDate=(TextView) convertView.findViewById(R.id.tvDate);
			viewHolder.tvTemperature=(TextView) convertView.findViewById(R.id.tvTemperature);
			viewHolder.tvWeather=(TextView) convertView.findViewById(R.id.tvWeather);
			convertView.setTag(viewHolder);
		}else{
			viewHolder=(ViewHolder) convertView.getTag();
		}
		viewHolder.tvDayOfWeek.setText(weather.getDayOfWeek());
		viewHolder.tvDate.setText(weather.getDate());
		viewHolder.tvTemperature.setText(weather.getTemperature());
		viewHolder.tvWeather.setText(weather.getWeather());
		return convertView;
	}
	private class ViewHolder{
		TextView tvDayOfWeek;
		TextView tvDate;
		TextView tvTemperature;
		TextView tvWeather;
	}
}
WeatherActivity.java
<span style="font-size:18px;">package com.example.weather;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import com.example.weather.adapter.WeatherAdapter;
import com.example.weather.moder.Weather;
import com.example.weather.util.HttpCallbackListener;
import com.example.weather.util.HttpUtil;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.LayoutAnimationController;
import android.view.animation.ScaleAnimation;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
public class WeatherActivity extends Activity {
	private EditText ecCity;
	private ImageButton btnQuery;
	private ListView lvFutureWeather;
	public static final int SHOW_RESPONSE=1;
	private List<Weather> data;
	private Handler handler=new Handler(){
		public void handleMessage(Message msg){
			switch (msg.what) {
			case SHOW_RESPONSE:
				String response=(String )msg.obj;
				if(response!=null){
					parseWithJSON(response);
					WeatherAdapter weatherAdapter=new WeatherAdapter
							(WeatherActivity.this, 
									R.layout.activity_weather_listitem, data);
					lvFutureWeather.setAdapter(weatherAdapter);
					ScaleAnimation scaleAnimation=new ScaleAnimation(0,1,0,1);
					scaleAnimation.setDuration(1000);
					LayoutAnimationController animationController  =  new
							LayoutAnimationController(
									scaleAnimation, 0.6f);
					lvFutureWeather.setLayoutAnimation(animationController);

				}
				break;

			default:
				break;
			}
		}

		private void parseWithJSON(String response) {
			// TODO Auto-generated method stub
			data=new ArrayList<Weather>();
			JsonParser parser=new JsonParser();//json解析器
			JsonObject obj=(JsonObject) parser.parse(response);
			//获取返回状态吗
			String resultcode=obj.get("resultcode").getAsString();
			//状态码如果是200说明数据返回成功
			if(resultcode!=null&&resultcode.equals("200")){
				JsonObject resultObj=obj.get("result").getAsJsonObject();
				JsonArray futureWeatherArray=resultObj.get("future").getAsJsonArray();
				for(int i=0;i<futureWeatherArray.size();i++){
					Weather  weather=new Weather();
					JsonObject weatherObject=futureWeatherArray.get(i).getAsJsonObject();
					weather.setDayOfWeek(weatherObject.get("week").getAsString());
					weather.setDate(weatherObject.get("date").getAsString());
					weather.setTemperature(weatherObject.get("temperature")
							.getAsString());
					weather.setWeather(weatherObject.get("weather")
							.getAsString());
					data.add(weather);
				}
			}
		}

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

	}
	public void initViews(){
		ecCity=(EditText) findViewById(R.id.etCity);
		btnQuery=(ImageButton)findViewById(R.id.btnQuery);
		lvFutureWeather=(ListView) findViewById(R.id.lvFutureWeather);
		 data=new ArrayList<Weather>();
	}
	private void setListeners(){
		btnQuery.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				String cityName=ecCity.getText().toString();  
				try {
					cityName = URLEncoder.encode("菏泽", "utf-8"); //这里我弄成默认的城市了,如果想根据输入的值进行搜索,,,可以把这句话换成cityName = URLEncoder.encode(cityName, "utf-8");


				} catch (UnsupportedEncodingException e1) {
					e1.printStackTrace();
				}
				System.out.println("lvFutureWeather="+lvFutureWeather);
				Toast.makeText(WeatherActivity.this, "success",
						Toast.LENGTH_LONG).show();
				String weatherUrl = "http://v.juhe.cn/weather/index?format=2&cityname="+cityName+"&key=ab9d7e2007472d723baf71fcdc4ba094";
				Toast.makeText(WeatherActivity.this, "success"+weatherUrl,
						Toast.LENGTH_LONG).show();
				HttpUtil.sendHttpRequest(weatherUrl, new HttpCallbackListener() {

					public void onFinish(String response) {
						// TODO Auto-generated method stub
						Message message=new Message();
						message.what=SHOW_RESPONSE;
						//将服务器返回的结果存放到Message中
						message.obj=response.toString();
						handler.sendMessage(message);
					}

					public void onError(Exception e) {
						// TODO Auto-generated method stub
						System.out.println("访问失败");
					}
				});
			}
		});
	}

}</span><strong>
</strong>

注意:  在进行查询输入城市名时一定要先改编码格式  列如
<span style="font-size:18px;">cityName = URLEncoder.encode("菏泽", "utf-8");</span>

源码地址:http://download.csdn.net/detail/zhupengqq/9560555

2017-02-25 11:37:41 v_xchen_v 阅读数 6479

学习参考资源:https://www.gitbook.com/book/zhangqx/mini-weather/details

前面我们已经做好了简单的布局,并且实现了获取internet上网页的网络数据的功能。接下来,我们绑定一个按钮,当点击这个按钮时,执行获取网络数据动作。

为我们顶部工具栏中的表示更新的图片绑定一个按钮,并设置监听和点击动作


步骤:

1.定义一个ImageView的变量,将这个变量与布局中表示更新的ImageView绑定
2.添加点击监听
3.添加点击后的响应动作


运行一下!

点击




2018-11-02 16:33:35 qq_33331424 阅读数 51

(IDE为Eclipse)
第一步:创建动画文件
在res文件夹下新建animator文件夹,新建animator的xml文件
在这里插入图片描述
点击下一步,界面里填写下图内容
在这里插入图片描述
文件建好之后填写如下内容:
(注意:android:drawable="@drawable/title_update"引用自己要旋转的资源文件)
在这里插入图片描述
第二步:修改主布局文件
在原先的更新ImageView控件处使用Framelayout布局,把原先的更新ImageView和ProgressBar控件添加进去,如下:
修改前:
在这里插入图片描述
修改后:
在这里插入图片描述
注意:分享ImageView控件的Android:layout_toLeftOf的属性改为新加的FrameLayout布局的id,更新按钮的ImageView的可见性设置为可见,progressBar设置为不可见(如上的Android:visibility属性的设置)
第三步:主activity内进行更新按钮的操作
1 添加ProgressBar并初始化,如下:
在这里插入图片描述
在这里插入图片描述
2 在更新按钮的事件处理下设置ImageView的可见性为隐藏,ProgressBar的可见属性为可见,添加如下选中区域的代码:
在这里插入图片描述
3 在更新天气的信息方法下设置ImageView的可见性为可见,ProgressBar的可见属性为隐藏,添加如下选中区域的代码:
在这里插入图片描述

2019-08-08 20:29:27 qq_38922435 阅读数 77

为了让自己的酷欧天气有个能够根据数据库动态添加TextView和按钮来显示已添加城市的界面,便开始着手于如标题所示的一个小Demo。
效果如图,能同时动态添加Button和TextView,还能通过动态添加的点击事件同时删除被点击的Button和TextView。

add.gif

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.administrator.button_add2.MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1">
        <ScrollView
            android:id="@+id/scrollView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scrollbars="none">
            <LinearLayout
                android:id="@+id/linearlayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:isScrollContainer="true"
                android:padding="10dp">
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">

                </LinearLayout>

            </LinearLayout>

        </ScrollView>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:id="@+id/btn_add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="#34ab8b"
            android:layout_margin="10dip"
            android:text="添加"
            android:textSize="18dp"
            android:textColor="#fff"/>
        <Button
            android:id="@+id/btn_edit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="#34ab8b"
            android:layout_margin="10dip"
            android:text="编辑"
            android:textSize="18dp"
            android:textColor="#fff"/>
    </LinearLayout>
</LinearLayout>
public class MainActivity extends AppCompatActivity {
    private LinearLayout linearLayout;
    //Button索引
    private LinkedList<Button> ListBtn_Show;
    //TextView索引
    private LinkedList<TextView> ListText_Def;
    private Button btn_add, btn_edit;
    //判断btn_edit的状态
    private int EDITSTATE = 0;

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

    private void inited() {
        linearLayout = (LinearLayout) findViewById(R.id.linearlayout);
        ListBtn_Show = new LinkedList<Button>();
        ListText_Def = new LinkedList<TextView>();
        btn_edit = (Button) findViewById(R.id.btn_edit);
        btn_add = (Button) findViewById(R.id.btn_add);
        btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addBtn();//动态添加按钮
            }
        });
        btn_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //判断编辑按钮的状态
                if (EDITSTATE == 0) {
                    btn_edit.setText("确定");
                    EDITSTATE = 1;
                } else if (EDITSTATE == 1) {
                    btn_edit.setText("编辑");
                    EDITSTATE = 0;
                }
            }
        });
    }

    private void addBtn() {//动态添加按钮
        //添加承载两个按钮的LinearLayout
        LinearLayout linear_btn = new LinearLayout(this);
        linear_btn.setOrientation(LinearLayout.HORIZONTAL);
        LinearLayout.LayoutParams liParam = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        linear_btn.setLayoutParams(liParam);

        //添加Button
        Button btnShow = new Button(this);
        LinearLayout.LayoutParams btnAddPar = new LinearLayout.LayoutParams
                (ViewGroup.LayoutParams.WRAP_CONTENT, 80, 3);//设置宽高及占比
        btnAddPar.setMargins(0, 10, 0, 10);
        btnShow.setLayoutParams(btnAddPar);
        btnShow.setText(ListBtn_Show.size() + "");
        btnShow.setTextColor(Color.argb(255, 255, 255, 255));
        btnShow.setBackgroundColor(Color.argb(255, 52, 171, 139));
        btnShow.setOnClickListener(new View.OnClickListener() {//动态添加点击事件
            @Override
            public void onClick(View view) {
                if (EDITSTATE == 1)
                    delBtn(view);//动态删除按钮
            }
        });
        linear_btn.addView(btnShow);//把btnShow添加到linear_btn中
        ListBtn_Show.add(btnShow);//把btnShow添加到索引中

        //添加TextView
        TextView textDef = new TextView(this);
        LinearLayout.LayoutParams btnDefPar = new LinearLayout.LayoutParams
                (ViewGroup.LayoutParams.WRAP_CONTENT, 80, 1);//设置宽高及占比
        btnDefPar.setMargins(0, 10, 0, 10);
        textDef.setLayoutParams(btnDefPar);
        textDef.setText("设为默认");
        textDef.setGravity(Gravity.CENTER);
        textDef.setTextColor(Color.argb(255, 255, 255, 255));
        textDef.setBackgroundColor(Color.argb(255, 52, 171, 139));
        textDef.setOnClickListener(new View.OnClickListener() {//动态添加点击事件
            @Override
            public void onClick(View view) {
                setDef(view);//设置默认
            }
        });
        linear_btn.addView(textDef);//把textDef添加到linear_btn中
        ListText_Def.add(textDef);//把textDef添加到索引中
        
        linearLayout.addView(linear_btn);//把linear_btn添加到外层linearLayout中
    }
    private void setDef(View view){//设置默认
        //遍历索引里的所有TextView
        for(int i=0;i<ListText_Def.size();i++){
            ListText_Def.get(i).setBackgroundColor(Color.argb(255, 52, 171, 139));
            ListText_Def.get(i).setText("设为默认");
            if(ListText_Def.get(i)==view){
                view.setBackgroundColor(Color.argb(255, 171, 52, 56));
                ListText_Def.get(i).setText("默认");
            }
        }
    }
    private void delBtn(View view) {//动态删除按钮
        if (view == null) {
            return;
        }
        int position = -1;
        for (int i = 0; i < ListBtn_Show.size(); i++) {
            if (ListBtn_Show.get(i) == view) {
                position = i;
                break;
            }
        }
        if (position >= 0) {
            ListBtn_Show.remove(position);//从索引中移除被删除的Button
            ListText_Def.remove(position);//从索引中移除被删除的TextView
            linearLayout.removeViewAt(position + 1);//在外出linearLayout删除内部指定位置所有控件
        }
    }
}

 

Android天气小部件

阅读数 3916

定位用的是百度SDKv4.2接口

博文 来自: u011603302
没有更多推荐了,返回首页