天气预报项目学习总结


SlidingMenu使用:

Java代码构造:

SlidingMenu构造方式:

SlidingMenumenu=new SlidingMenu(context);

 

+++++++++++++++++++++++++++++++++++++++++++

SlidingMenumenu=new SlidingMenu(this);

        //设置侧滑的菜单的布局文件

        menu.setMenu(R.layout.sliding_left);

        //设置侧滑的方式

        menu.setMode(SlidingMenu.LEFT_RIGHT);

        //设置右侧菜单

        menu.setSecondaryMenu(R.layout.sliding_right);

        //设置窗口剩余的宽度

        //menu.setBehindOffset(200);

        menu.setBehindWidth(150);

        //设置侧滑的屏幕的位置

        menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);

        //把侧滑菜单添加到活动窗口上

        //menu.attachToActivity(this,SlidingMenu.SLIDING_CONTENT);

        menu.attachToActivity(this,SlidingMenu.SLIDING_WINDOW);

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++

SlidingMenu常用属性介绍:
menu.setMode(SlidingMenu.LEFT);//设置左滑菜单
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);//设置滑动的屏幕范围,该设置为全屏区域都可以滑动
menu.setShadowDrawable(R.drawable.shadow);//设置阴影图片
menu.setShadowWidthRes(R.dimen.shadow_width);//设置阴影图片的宽度
menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);//SlidingMenu划出时主页面显示的剩余宽度
menu.setBehindWidth(400);//设置SlidingMenu菜单的宽度
menu.setFadeDegree(0.35f);//SlidingMenu滑动时的渐变程度
menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);//使SlidingMenu附加在Activity上
menu.setMenu(R.layout.menu_layout);//设置menu的布局文件
menu.toggle();//动态判断自动关闭或开启SlidingMenu
menu.showMenu();//显示SlidingMenu
menu.showContent();//显示内容
menu.setOnOpenListener(onOpenListener);//监听slidingmenu打开
关于关闭menu有两个监听,简单的来说,对于menuclose事件,一个是when,一个是after
menu.OnClosedListener(OnClosedListener);//监听slidingmenu关闭时事件
menu.OnClosedListener(OnClosedListener);//监听slidingmenu关闭后事件

左右都可以划出SlidingMenu菜单只需要设置
menu.setMode(SlidingMenu.LEFT_RIGHT);属性,然后设置右侧菜单的布局文件
menu.setSecondaryShadowDrawable(R.drawable.shadowright);//右侧菜单的阴影图片

设置SlidingMenu属性
sm = getSlidingMenu();
//如果只显示左侧菜单就是用LEFT,右侧就RIGHT,左右都支持就LEFT_RIGHT
sm.setMode(SlidingMenu.LEFT_RIGHT);//设置菜单滑动模式,菜单是出现在左侧还是右侧,还是左右两侧都有
sm.setShadowDrawable(R.drawable.shadow);//设置阴影的图片资源
sm.setShadowWidthRes(R.dimen.shadow_width);//设置阴影图片的宽度
//sm.setBehindWidth(200);//设置菜单的宽
sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);//SlidingMenu划出时主页面显示的剩余宽度
sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);//设置滑动的区域

支持右侧划出菜单:
//SlidingMenu可以同时支持划出左右两侧的菜单,互不冲突,而且动画优美,体验良好。
sm.setSecondaryMenu(R.layout.menu_frame2);//设置右侧菜单
sm.setSecondaryShadowDrawable(R.drawable.shadowright);//设置右侧菜单阴影的图片资源
//右侧SlidingMenu的Fragment
getSupportFragmentManager().beginTransaction().replace(R.id.menu_frame2, newSampleListFragment()).commit();

slidingMenu= getSlidingMenu();
//设置是左滑还是右滑,还是左右都可以滑
slidingMenu.setMode(SlidingMenu.LEFT_RIGHT);
//设置阴影宽度
slidingMenu.setShadowWidth(getWindowManager().getDefaultDisplay().getWidth() /40);
//设置左菜单阴影图片
slidingMenu.setShadowDrawable(R.drawable.shadow);
//设置右菜单阴影图片
slidingMenu.setSecondaryShadowDrawable(R.drawable.right_shadow);
//设置菜单占屏幕的比例
slidingMenu.setBehindOffset(getWindowManager().getDefaultDisplay().getWidth() /5);
//设置滑动时菜单的是否淡入淡出
slidingMenu.setFadeEnabled(true);
//设置淡入淡出的比例
slidingMenu.setFadeDegree(0.4f);
//设置滑动时拖拽效果
slidingMenu.setBehindScrollScale(0);
//设置要使菜单滑动,触碰屏幕的范围
slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);

 

XML布局方式:



×××××××××××××××××××××××××××××××××××××××××

Gson:

Gson使用步骤:

 

1.    借助在线json格式化工具,查看返回的json字符串的格式

 

 

 

在线json格式化工具:

http://tool.oschina.net/codeformat/json

json实体数据封装的工具

http://www.bejson.com/

===================================================================================

 

2.   根据json字符串的格式,构造相对应的实体类Bean;

 

public class Employee {

    private String empID;

    private String name;

    private booleanpermanent;

    private Addressaddress;

    privateList phoneNumbers;

    private String role;

    private String[]cities;

    private Propertiesproperties;

    public StringgetEmpID() {

        return empID;

    }

    public voidsetEmpID(String empID) {

        this.empID = empID;

    }

    public String getName(){

        return name;

    }

    public voidsetName(String name) {

        this.name = name;

    }

    public booleanisPermanent() {

        return permanent;

    }

    public voidsetPermanent(boolean permanent) {

        this.permanent =permanent;

    }

    public AddressgetAddress() {

        return address;

    }

    public voidsetAddress(Address address) {

        this.address =address;

    }

    publicList getPhoneNumbers() {

        returnphoneNumbers;

    }

    public voidsetPhoneNumbers(List phoneNumbers) {

        this.phoneNumbers =phoneNumbers;

    }

    public String getRole(){

        return role;

    }

    public voidsetRole(String role) {

        this.role = role;

    }

    public String[]getCities() {

        return cities;

    }

    public voidsetCities(String[] cities) {

        this.cities =cities;

    }

    public PropertiesgetProperties() {

        return properties;

    }

    public voidsetProperties(Properties properties) {

        this.properties =properties;

    }

    public Employee() {

        super();

        // TODOAuto-generated constructor stub

    }

    public Employee(StringempID, String name, boolean permanent,

            Addressaddress, List phoneNumbers, String role,

            String[]cities, Properties properties) {

        super();

        this.empID = empID;

        this.name = name;

        this.permanent =permanent;

        this.address =address;

        this.phoneNumbers =phoneNumbers;

        this.role = role;

        this.cities =cities;

        this.properties =properties;

    }

 

    public static classAddress {

        private Stringstreet;

        private Stringcity;

        private Stringzipcode;

        public StringgetStreet() {

            return street;

        }

        public voidsetStreet(String street) {

            this.street =street;

        }

        public StringgetCity() {

            return city;

        }

        public voidsetCity(String city) {

            this.city =city;

        }

        public StringgetZipcode() {

            return zipcode;

        }   

        public voidsetZipcode(String zipcode) {

            this.zipcode =zipcode;

        }

        publicAddress(String street, String city, String zipcode) {

            super();

            this.street =street;

            this.city =city;

            this.zipcode =zipcode;

        }

        public Address() {

            super();

            // TODOAuto-generated constructor stub

        }

        @Override

        public StringtoString() {

            return"Address [street=" + street + ", city=" + city

                    +", zipcode=" + zipcode + "]";

        }

    }

    public static classProperties {

        private String age;

        private Stringsalary;

        public StringgetAge() {

            return age;

        }

        public voidsetAge(String age) {

            this.age = age;

        }

 

        public StringgetSalary() {

            return salary;

        }

        public voidsetSalary(String salary) {

            this.salary =salary;

        }

        publicProperties(String age, String salary) {

            super();

            this.age = age;

            this.salary =salary;

        }

        public Properties(){

            super();

            // TODOAuto-generated constructor stub

        }

        @Override

        public StringtoString() {

            return"Properties [age=" + age + ", salary=" + salary +"]";

        }

    }

    @Override

    public StringtoString() {

        return"Employee [empID=" + empID + ", name=" + name + ",permanent="

                + permanent+ ", address=" + address + ", phoneNumbers="

                +phoneNumbers + ", role=" + role + ", cities="

                +Arrays.toString(cities) + ", properties=" + properties +"]";

    }

 

}

===================================================================================

 

3.   构建Gson对象将Json字符串解析为实体类:

 

public class GsonTestEmp {

public static voidmain(String[] args) {

     //构建Gson对象

     Gson gson=new Gson();

     try {

         String jsonStr=new String(Files.readAllBytes(Paths.get("employee.txt")));

         //System.out.println(jsonStr);

        

         Employeeemployee=gson.fromJson(jsonStr, Employee.class);

    

         System.out.println(employee.toString());

        

     } catch (IOExceptione) {

         e.printStackTrace();

     }

}

}

 

×××××××××××××××××××××××××××××××××××××××××

 

Volley使用:

1.   字符串请求StringRequest:

第1步创建一个请求的队列

创建一个volley的请求对象

将请求对象添加到请求队列中

 

++++++++++++++++++++++++++++++++++++++++++++++++++

public class MainActivity extends Activity {

    //第1步创建一个请求的队列

    RequestQueue queue=null;

    @Override

    protected voidonCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        queue=Volley.newRequestQueue(this);

    }

   

    public void load(Viewview){

        StringRequestrequest=null;

        try {

            String cityname= URLEncoder.encode("北京","utf8");

            String url ="http://op.juhe.cn/onebox/weather/query?cityname="+cityname+"&dtype=&key=ea8441cb939845649b04948972f34db6";

            //2.创建一个volley的请求对象

             request= new StringRequest(url,

                    newListener() {

 

                        @Override

                        publicvoid onResponse(String response) {

                            Gsongson=new Gson();

                            WeatherBeanbean=gson.fromJson(response, WeatherBean.class);

                            Log.i("TAG:weather",bean.toString());

                        }

                    }, newErrorListener() {

                        @Override

                        publicvoid onErrorResponse(VolleyError error) {

                                Log.i("TAG:error",error.getMessage());

                        }

                    });

        } catch (Exceptione) {

            e.printStackTrace();

        }

        //3.将请求对象添加到请求队列中

        queue.add(request);

    }

}

===================================================================================

 

2.   图片请求ImageRequest:

创建请求队列

获得ImageView控件

创建图片请求ImageRequest对象

将图片请求ImageRequest对象放入请求队列

 

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++

public class MainActivity extends Activity {

 

RequestQueue queue=null;

ImageViewimageView_test=null;

@Override

protected voidonCreate(Bundle savedInstanceState) {

     super.onCreate(savedInstanceState);

     setContentView(R.layout.activity_main);

     queue=Volley.newRequestQueue(this);

     imageView_test=(ImageView)findViewById(R.id.imageView_test);

}

 

public voidloadimage1(View view){

     Stringurl="http://172.60.50.50:8080/MusicServer/images/disanji.jpg";

     ImageRequestrequest=new ImageRequest(url, new Listener() {

 

         @Override

         public voidonResponse(Bitmap response) {

             imageView_test.setImageBitmap(response);

         }

     }, 0, 0,Config.ARGB_8888, new Response.ErrorListener() {

 

         @Override

         public voidonErrorResponse(VolleyError error) {

             Log.i("TAG",error.getMessage());

         }

     });

     queue.add(request);

}

}

===================================================================================

 

3.   Json请求 jsonRequest

创建请求队列RequestQueue

创建JsonRequest对象

将JsonRequest放入请求队列RequestQueue

 

 

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

public class SecondActivity extends Activity {

RequestQueue queue=null;

@Override

protected voidonCreate(Bundle savedInstanceState) {

     super.onCreate(savedInstanceState);

     setContentView(R.layout.activity_second);

     queue=Volley.newRequestQueue(this);

}

public void loadjson(Viewview){

     JsonRequestjsonRequest=null;

     try {

         String cityname =URLEncoder.encode("北京","utf8");

         String url ="http://op.juhe.cn/onebox/weather/query?cityname="

                 + cityname+ "&dtype=&key=ea8441cb939845649b04948972f34db6";

          jsonRequest = new JsonObjectRequest(url,

                 null, newListener() {

 

                     @Override

                     publicvoid onResponse(JSONObject response) {

                         Log.i("TAG",response.toString());

                     }

                 }, newErrorListener() {

 

                     @Override

                     public void onErrorResponse(VolleyErrorerror) {

                         Log.e("ERROR",error.getMessage());

                     }

                 });

     } catch (Exception e){

         e.printStackTrace();

     }

     queue.add(jsonRequest);

}

 

}

===================================================================================

 

4.   自定义Volley请求:

自定义请求类继承Request累

重写构造方法

仿照StringRequest重写parseNetworkResponse方法

重写deliverResponse方法

和StringRequest一样使用

 

 

++++++++++++++++++++++++++++++++++++++++++++++++++++++

package com.tarena.karen.request;

 

import java.io.UnsupportedEncodingException;

 

import com.android.volley.NetworkResponse;

import com.android.volley.ParseError;

import com.android.volley.Request;

import com.android.volley.Response;

import com.android.volley.Response.ErrorListener;

import com.android.volley.Response.Listener;

import com.android.volley.toolbox.HttpHeaderParser;

import com.google.gson.Gson;

import com.tarena.karen.entity.WeatherBean;

 

public class WeatherRequest extends Request {

    privateListener mListener;

 

    publicWeatherRequest(int method, String url,

            ListenermListener, ErrorListener listener) {

        super(method, url,listener);

        this.mListener =mListener;

    }

 

    publicWeatherRequest(String url, Listener mListener,

            ErrorListenerlistener) {

        this(Method.GET,url, mListener, listener);

    }

 

    @Override

    protectedResponse parseNetworkResponse(

            NetworkResponseresponse) {

        String jsonString;

        try {

            jsonString =new String(response.data,

                    HttpHeaderParser.parseCharset(response.headers));

            Gson gson = newGson();

            WeatherBeanbean = gson.fromJson(jsonString, WeatherBean.class);

            returnResponse.success(bean,

                    HttpHeaderParser.parseCacheHeaders(response));

        } catch (UnsupportedEncodingExceptione) {

            e.printStackTrace();

            returnResponse.error(new ParseError(e));

        }

    }

 

    @Override

    protected voiddeliverResponse(WeatherBean response) {

        mListener.onResponse(response);

    }

 

}

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

 

public class MainActivity extends Activity {

 

    RequestQueuequeue=null;

    @Override

    protected voidonCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        queue=Volley.newRequestQueue(this);

   

    }

    public voidloadweather(View view) throws UnsupportedEncodingException{

        Stringcityname=URLEncoder.encode("北京", "utf8");

        Stringurl="http://op.juhe.cn/onebox/weather/query?cityname="+cityname+"&dtype=&key=ea8441cb939845649b04948972f34db6";

        WeatherRequestrequest=new WeatherRequest(url, new Listener() {

 

            @Override

            public voidonResponse(WeatherBean response) {

                Log.i("TAG",response.toString());

            }

        }, newErrorListener() {

 

            @Override

            public voidonErrorResponse(VolleyError error) {

                Log.e("ERROR",error.getMessage());

            }

        });

        queue.add(request);

    }

}

 

===================================================================================

 

Volley的其他图片处理方式:

1.   Imageloader:

创建请求队列RequestQueue;

  创建ImageLoader对象,同时构建ImageCache重写putBitmap和getBitmap方法

  创建ImageListener对象

  执行ImageLoader对象的loader.get(url, listener)方法

+++++++++++++++++++++++++++++++++++++++++++++++++++++++

public class ImageLoaderActivity extends Activity {

    ImageViewimageView_loader=null;

    RequestQueuequeue=null;

    @Override

    protected voidonCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_image_loader);

        imageView_loader=(ImageView)findViewById(R.id.imageView_loader);

        queue=Volley.newRequestQueue(this);

    }

    public voidimageloader(View view){

        ImageLoaderloader=new ImageLoader(queue, new ImageCache() {           

             int maxSize=1024*1024*4;

             LruCache cache=newLruCache(maxSize){

                protectedint sizeOf(String key, Bitmap value) {

                    returnvalue.getRowBytes()*value.getHeight();

                };

             };

            @Override

            public voidputBitmap(String url, Bitmap bitmap) {

                //把加载成功的图片存入缓存

                cache.put(url,bitmap);

            }

           

            @Override

            public BitmapgetBitmap(String url) {

                //从缓存中获得图片

                returncache.get(url);

            }

        });

        Stringurl="http://172.60.50.50:8080/MusicServer/images/disanji.jpg";

       

        ImageListenerlistener=ImageLoader.getImageListener(

                imageView_loader,

                R.drawable.ic_launcher,

                R.drawable.ic_launcher);

       

        loader.get(url,listener);

    }

 

}

+++++++++++++++++++++++++++++++++++++++++++++++++++++++

2.   使用自定义的NetworkImageView

在Xml布局中使用NetworkImageView:

在java代码中获得NetworkImageView对象

创建请求队列RequestQueue

创建ImageLoader对象

执行NetworkImageView对象的.setImageUrl(url,loader)方法

 

+++++++++++++++++++++++++++++++++++++++++++++++++++++

   

       android:id="@+id/imageview_network"

       android:layout_width="80dp"

       android:layout_height="80dp"

       android:layout_alignParentTop="true"

       android:layout_centerHorizontal="true"/>  

 

++++++++++++++++++++++++++++++++++++++++++++++++++++

public class NetWorkImageActivity extends Activity {

 

    NetworkImageViewimageView=null;

    RequestQueuequeue=null;

    @Override

    protected voidonCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_net_work_image);

        imageView=(NetworkImageView)findViewById(R.id.imageview_network);

       

        queue=Volley.newRequestQueue(this);

        imageView.setDefaultImageResId(R.drawable.ic_launcher);

        imageView.setErrorImageResId(R.drawable.ic_launcher);

    }

    public voidloadnetwork(View view){

        ImageLoaderloader=new ImageLoader(queue, new ImageCache() {

            intmaxSize=1024*1024*4;

            LruCache cache=new LruCache(maxSize){

                protectedint sizeOf(String key, Bitmap value) {

                    returnvalue.getRowBytes()*value.getHeight();

                };

            };

            @Override

            public voidputBitmap(String url, Bitmap bitmap) {

                cache.put(url,bitmap);

            }

           

            @Override

            public BitmapgetBitmap(String url) {

                returncache.get(url);

            }

        });

        Stringurl="http://172.60.50.50:8080/MusicServer/images/disanji.jpg";

        imageView.setImageUrl(url,loader);

    }

 

}

 

 

 

 

PullToRefreshListView:
 
 
布局中使用PullToRefreshListView

建立PullToRefreshListView的ItemView的布局

在Java代码中获得PullToRefreshListView对象
创建适配器
将适配器与PullToRefreshListView对象关联
设置上拉刷新,下拉加载监听
++++++++++++++++++++++++++++++++++++++++++++++++++++++
     
  
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/refresh_listview"
         >
    

 

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

   android:layout_width="match_parent"

   android:layout_height="50dp"

    android:orientation="horizontal"

   android:weightSum="5" >

 

   

       android:id="@+id/image_item_weather"

       android:layout_width="wrap_content"

       android:layout_height="match_parent"

       android:paddingLeft="10dp"

       android:src="@drawable/sunny" />

 

   

       android:id="@+id/textview_item_condition"

       android:layout_width="0dp"

       android:layout_height="match_parent"

       android:layout_weight="1"

       android:gravity="center"

        android:text="晴" />

 

   

       android:id="@+id/textview_item_temp"

       android:layout_width="0dp"

       android:layout_height="match_parent"

       android:layout_weight="1"

       android:gravity="center"

       android:text="21/18" />

 

   

       android:id="@+id/textview_item_weekday"

       android:layout_width="0dp"

       android:layout_height="match_parent"

       android:layout_weight="1"

       android:gravity="center_vertical"

       android:text="星期三"/>

 

 

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

 

public class WeatherAdapter extends BaseAdapter {

    Listweathers=new ArrayList();

    LayoutInflaterlayoutInflater=null;

    publicWeatherAdapter(Context context) {

        layoutInflater=LayoutInflater.from(context);

    }

    public voidaddWeathers(List weatherList,boolean isClear){

        if(isClear){

            weathers.clear();

            weathers.addAll(weatherList);

        }else{

            weathers.addAll(weatherList);

        }

        notifyDataSetChanged();

    }

   

    @Override

    public int getCount() {

        returnweathers.size();

    }

 

    @Override

    public WeathergetItem(int position) {

        returnweathers.get(position);

    }

 

    @Override

    public longgetItemId(int position) {

        return position;

    }

 

    @Override

    public View getView(intposition, View convertView, ViewGroup parent) {

        ViewHolderholder=null;

        if(convertView==null){

            holder=newViewHolder();

            convertView=layoutInflater.inflate(R.layout.inflate_weather_item,null);

            holder.imageview_codition=(ImageView)convertView.findViewById(R.id.image_item_weather);

            holder.textview_condition=(TextView)convertView.findViewById(R.id.textview_item_condition);

            holder.textview_temp=(TextView)convertView.findViewById(R.id.textview_item_temp);

            holder.textview_weekday=(TextView)convertView.findViewById(R.id.textview_item_weekday);

            convertView.setTag(holder);

        }else{

            holder=(ViewHolder)convertView.getTag();

        }

        Weatherweather=weathers.get(position);

        String condition=weather.getInfo().getDay()[0];

        if(condition.equals("0")){

            holder.imageview_codition.setImageResource(R.drawable.sunny);

        }elseif(condition.equals("1")){

            holder.imageview_codition.setImageResource(R.drawable.cloudy);         

        }elseif(condition.equals("2")){

            holder.imageview_codition.setImageResource(R.drawable.lotcloudy);

        }elseif(condition.equals("3")){

            holder.imageview_codition.setImageResource(R.drawable.rain);

        }

        holder.textview_condition.setText(weather.getInfo().getDay()[1]);

        holder.textview_temp.setText(weather.getInfo().getDay()[2]+"/"+weather.getInfo().getNight()[2]);

        holder.textview_weekday.setText(weather.getWeek());

        return convertView;

    }

 

    public classViewHolder{

        ImageViewimageview_codition=null;

        TextViewtextview_weekday=null;

        TextViewtextview_condition=null;

        TextViewtextview_temp=null;

    }

}

 

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

public class MainActivity extends Activity {

    PullToRefreshListViewrefreshListView = null;

    WeatherAdapter adapter= null;

 

    @Override

    protected voidonCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        initialUI();

    }

 

    private voidinitialUI() {

        adapter = newWeatherAdapter(this);

        refreshListView =(PullToRefreshListView) findViewById(R.id.refresh_listview);

        refreshListView.setAdapter(adapter);

        // 加载数据

        HttpManager.loadWeathers(this,"北京", newLoadWeatherListener() {

            @Override

            public voidOnWeatherLoadEnd(WeatherBean bean) {

                Listweathers = bean.getResult().getData()

                        .getWeather();

                adapter.addWeathers(weathers,true);

            }

        });

        // //实现下拉刷新功能

        //refreshListView.setOnRefreshListener(new

        //OnRefreshListener() {

        // @Override

        // public voidonRefresh(final PullToRefreshBase refreshView)

        // {

        // //在该回调方法中加入网络请求的代码,请求服务器端的新的数据

        // //以实现下拉刷新

        //

        //refreshListView.onRefreshComplete();

        //HttpManager.loadWeathers(MainActivity.this,

        // "北京",

        // new LoadWeatherListener(){

        // @Override

        // public voidOnWeatherLoadEnd(WeatherBean bean) {

        //

        //List weathers=bean.getResult().getData().getWeather();

        //adapter.addWeathers(weathers, false);

        // }

        // });

        // }

        // });

 

        refreshListView.setMode(Mode.BOTH);

        // 实现下拉刷新和上拉加载

        refreshListView.setOnRefreshListener(newOnRefreshListener2() {

 

            public voidonPullDownToRefresh(final PullToRefreshBase refreshView) {

                // 实现下拉刷新

                refreshListView.onRefreshComplete();

                HttpManager.loadWeathers(MainActivity.this,"北京", newLoadWeatherListener() {                

                    @Override

                    publicvoid OnWeatherLoadEnd(WeatherBean bean) {

                        Listweathers=bean.getResult().getData().getWeather();

                        adapter.addWeathers(weathers,false);

                       

                        refreshView.getLoadingLayoutProxy(true,false)

                        .setLastUpdatedLabel("正在加载内容.....");

                    }

                });

            }

 

            @Override

            public voidonPullUpToRefresh(final PullToRefreshBase refreshView) {

                refreshListView.onRefreshComplete();

                // 实现上拉加载

                HttpManager.loadWeathers(MainActivity.this,"北京", newLoadWeatherListener() {                

                    @Override

                    publicvoid OnWeatherLoadEnd(WeatherBean bean) {

                        Listweathers=bean.getResult().getData().getWeather();

                        adapter.addWeathers(weathers,false);

                        refreshView.getLoadingLayoutProxy(false,true).setPullLabel("上拉加载中......");

                    }

                });

            }

        });

    }

}

 

 

 

 

        //解析自定义的布局文件转换成一个view对象

        realtime_view=getLayoutInflater().inflate(R.layout.realweather_layout,

                listview_weather,

                false);

       

        adapter=newWeatherAdapter(this);

        pullToRefreshListView=(PullToRefreshListView)findViewById(R.id.pull_refresh_listview);

        listview_weather=pullToRefreshListView.getRefreshableView();

        listview_weather.setAdapter(adapter);

        //将view对象作为listview的Header

        listview_weather.addHeaderView(realtime_view);

 

 

绘制折线图:

使用achartengine-1.1.0.jar

 

import org.achartengine.ChartFactory;

import org.achartengine.GraphicalView;

import org.achartengine.chart.PointStyle;

import org.achartengine.model.XYMultipleSeriesDataset;

import org.achartengine.model.XYSeries;

import org.achartengine.renderer.XYMultipleSeriesRenderer;

import org.achartengine.renderer.XYSeriesRenderer;

 

import android.app.Activity;

import android.graphics.Color;

import android.os.Bundle;

public class MainActivity extends Activity {

 

    @Override

    protected voidonCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

       

        lineView();

    }

 

    // 折线图

    public void lineView(){

        // 同样是需要数据dataset和视图渲染器renderer

        XYMultipleSeriesDatasetmDataset = new XYMultipleSeriesDataset();

        XYSeries series =new XYSeries("第一条线");

        series.add(1, 6);

        series.add(2, 5);

        series.add(3, 7);

        series.add(4, 4);      

        mDataset.addSeries(series);

        XYSeries seriesTwo= new XYSeries("第二条线");

        seriesTwo.add(1,4);

        seriesTwo.add(2,6);

        seriesTwo.add(3,3);

        seriesTwo.add(4,7);

        mDataset.addSeries(seriesTwo);

 

        XYMultipleSeriesRenderermRenderer = new XYMultipleSeriesRenderer();

        // 设置图表的X轴的当前方向

        mRenderer

                .setOrientation(XYMultipleSeriesRenderer.Orientation.HORIZONTAL);

        mRenderer.setXTitle("日期");// 设置为X轴的标题

        mRenderer.setYTitle("价格");// 设置y轴的标题

        mRenderer.setAxisTitleTextSize(20);//设置轴标题文本大小

        mRenderer.setChartTitle("价格走势图");// 设置图表标题

        mRenderer.setChartTitleTextSize(30);//设置图表标题文字的大小

        mRenderer.setLabelsTextSize(18);//设置标签的文字大小

        mRenderer.setLegendTextSize(20);//设置图例文本大小

        mRenderer.setPointSize(10f);//设置点的大小

        mRenderer.setYAxisMin(0);//设置Y轴起点

        mRenderer.setYAxisMax(15);

        mRenderer.setYLabels(10);//设置Y轴刻度个数(貌似不太准确)

        mRenderer.setXAxisMax(5);

        mRenderer.setShowGrid(true);//显示网格

        // 将x标签栏目显示如:1,2,3,4替换为显示1月,2月,3月,4月

        mRenderer.addXTextLabel(1,"1月");

        mRenderer.addXTextLabel(2,"2月");

        mRenderer.addXTextLabel(3,"3月");

        mRenderer.addXTextLabel(4,"4月");

        mRenderer.setXLabels(0);//设置只显示如1月,2月等替换后的东西,不显示1,2,3等

        mRenderer.setMargins(newint[] {20, 30, 30, 20 });// 设置视图位置上左下右

 

        XYSeriesRenderer r= new XYSeriesRenderer();// (类似于一条线对象)

        r.setColor(Color.BLUE);//设置颜色

        r.setPointStyle(PointStyle.CIRCLE);//设置点的样式

        r.setFillPoints(true);//填充点(显示的点是空心还是实心)

        r.setDisplayChartValues(true);//将点的值显示出来

        r.setChartValuesSpacing(10);//显示的点的值与图的距离

        r.setChartValuesTextSize(25);//点的值的文字大小

 

        //r.setFillBelowLine(true);//是否填充折线图的下方

        //r.setFillBelowLineColor(Color.GREEN);//填充的颜色,如果不设置就默认与线的颜色一致

        r.setLineWidth(3);//设置线宽

        mRenderer.addSeriesRenderer(r);

 

        XYSeriesRendererrTwo = new XYSeriesRenderer();// (类似于一条线对象)

        rTwo.setColor(Color.GRAY);//设置颜色

        rTwo.setPointStyle(PointStyle.CIRCLE);//设置点的样式

        rTwo.setFillPoints(true);//填充点(显示的点是空心还是实心)

        rTwo.setDisplayChartValues(true);//将点的值显示出来

        rTwo.setChartValuesSpacing(10);//显示的点的值与图的距离

        rTwo.setChartValuesTextSize(25);//点的值的文字大小

 

        //rTwo.setFillBelowLine(true);//是否填充折线图的下方

        //rTwo.setFillBelowLineColor(Color.GREEN);//填充的颜色,如果不设置就默认与线的颜色一致

        rTwo.setLineWidth(3);//设置线宽

 

        mRenderer.addSeriesRenderer(rTwo);

 

        GraphicalView view= ChartFactory.getLineChartView(this, mDataset,

                mRenderer);

        view.setBackgroundColor(Color.BLACK);

        setContentView(view);

    }

}

 

===========================================================

你可能感兴趣的:(学习笔记)