新闻客户端

一.
学习目标:掌握AsyncHttpClient和SmartImageView的使用。

二.
1.创建一个名为”news”的应用程序,设计交互式的页面,对应的布局文件如下:

<?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/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
  android:orientation="vertical"
    tools:context="com.example.bz0209.anew.MainActivity">

   <FrameLayout
       android:layout_width="match_parent"
       android:layout_height="match_parent">
       <LinearLayout
           android:id="@+id/loading"
           android:visibility="invisible"
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:gravity="center"
           android:orientation="vertical">
           <ProgressBar
               android:layout_width="wrap_content"
               android:layout_height="wrap_content" />
           <TextView
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:text="加载..."/>

       </LinearLayout>
      <ListView
          android:id="@+id/lv_news"
          android:layout_width="match_parent"
          android:layout_height="match_parent"></ListView>
   </FrameLayout>
</LinearLayout>

2.创建ListView Item的布局,ListView 的Item 布局文件news_item.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="65dp">
    <com.loopj.android.image.SmartImageView
        android:id="@+id/siv_icon"
        android:layout_width="80dp"
        android:layout_height="60dp"
        android:scaleType="centerCrop"
        android:src="@mipmap/ic_launcher"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"></com.loopj.android.image.SmartImageView>
    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_marginTop="10dp"
        android:layout_toRightOf="@id/siv_icon"
        android:ellipsize="end"
        android:maxLength="20"
        android:singleLine="true"
        android:text="我是标题"
        android:textColor="#000000"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/tv_description"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_title"
        android:layout_marginLeft="5dp"
        android:layout_marginTop="5dp"
        android:layout_toRightOf="@id/siv_icon"
        android:ellipsize="end"
        android:maxLength="16"
        android:maxLines="1"
        android:text="我是描述"
        android:textColor="#99000000"
        android:textSize="14sp" />

    <TextView
        android:id="@+id/tv_type"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="5dp"
        android:layout_marginRight="10dp"
        android:text="评论"
        android:textColor="#99000000"
        android:textSize="12sp" />

</RelativeLayout>

3.编写界面交互代码MainActivity,代码如下:

package com.example.bz0209.anew;

import android.app.Activity;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.image.SmartImageView;

import java.io.ByteArrayInputStream;
import java.util.List;

public class MainActivity extends Activity {
    private ListView lv_news;
    private LinearLayout loading;
    private List<NewsInfo> newsInfos;

    private class NewsAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return newsInfos.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view=View.inflate(MainActivity.this,R.layout.news_item,null);
            SmartImageView siv=(SmartImageView) view.findViewById(R.id.siv_icon);
            TextView tv_title=(TextView) view.findViewById(R.id.tv_title);
            TextView tv_description=(TextView) view.findViewById(R.id.tv_description);
            TextView tv_type=(TextView) view.findViewById(R.id.tv_type);
            NewsInfo newsInfo=newsInfos.get(position);
            siv.setImageUrl(newsInfo.getIconPath(),R.drawable.a,R.drawable.b);
            tv_title.setText(newsInfo.getTitle());
            tv_description.setText(newsInfo.getDescription());
            int type=newsInfo.getType();
            switch (type){
                case 1:
                    tv_type.setText("评论"+newsInfo.getComment());
                    break;
                case 2:
                    tv_type.setTextColor(Color.RED);
                    tv_type.setText("专题");
                    break;
                case 3:
                    tv_type.setTextColor(Color.BLUE);
                    tv_type.setText("LIVE");
                    break;
            }
            return view;
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv_news = (ListView) findViewById(R.id.lv_news);
        loading = (LinearLayout) findViewById(R.id.loading);
        fillData2();

    }
    private void fillData2(){
        AsyncHttpClient asyncHttpClient=new AsyncHttpClient();
        asyncHttpClient.get(getString(R.string.serverurl), new AsyncHttpResponseHandler() {

            public void onSuccess(String content) {
                super.onSuccess(content);
                byte[] bytes=content.getBytes();
                ByteArrayInputStream bais=new ByteArrayInputStream(bytes);
                newsInfos=NewsInfoService.getNewsInfos(bais);
                if (newsInfos==null){
                    Toast.makeText(MainActivity.this,"解析失败",0).show();
                }else {
                    loading.setVisibility(View.INVISIBLE);
                    lv_news.setAdapter(new NewsAdapter());
                }

            }
            public void onFailure(Throwable error,String content){
                super.onFailure(error,content);
                Toast.makeText(MainActivity.this,"失败",0).show();
            }
        });
    }
}



4.创建NewsInfo类:

public class NewsInfo {
    private String iconPath;
    private String title;
    private String description;
    private int type;
    private long comment;

    public String getIconPath() {
        return iconPath;
    }

    public void setIconPath(String iconPath) {
        this.iconPath = iconPath;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public long getComment() {
        return comment;
    }

    public void setComment(long comment) {
        this.comment = comment;
    }

    public void getComment(long l) {
    }
}

5.创建工具类解析xml文件,需要使用XmlParser对象解析出xml里面的内容并设置到相应的JavaBean中,将解析操作的逻辑放在NewsInfoService中:


import android.util.Xml;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import static android.R.attr.type;

/**
 * Created by Administrator on 2017/5/22.
 */

public class NewsInfoService {
    public static List<NewsInfo> getNewInfos(InputStream is){
        XmlPullParser parser= Xml.newPullParser();
        try {
            parser.setInput(is,"utf-8");
           // parser.setInput(is,"utf-8");
            int type=parser.getEventType();
            List<NewsInfo> newsInfos=null;
            NewsInfo newsInfo=null;
            while (type!=XmlPullParser.END_DOCUMENT){
                switch (type){
                    case XmlPullParser.START_TAG:
                        if ("news".equals(parser.getName())){
                            newsInfo= new NewsInfo();
                        }else if ("newsInfo".equals(parser.getName())){
                            newsInfo=new NewsInfo();
                        }else if("icon".equals(parser.getName())){
                            String icon=parser.nextText();
                            newsInfo.setIconPath(icon);
                        }else if ("title".equals(parser.getName())){
                            String title=parser.nextText();
                            newsInfo.setTitle(title);
                        }else if ("content".equals(parser.getName())){
                            String description=parser.nextText();
                            newsInfo.setDescription(description);
                        }else if ("type".equals(parser.getName())){
                            String newsType=parser.nextText();
                            newsInfo.setType(Integer.parseInt(newsType));
                        }else if ("cumment".equals(parser.getName())){
                            String comment=parser.nextText();
                            newsInfo.getComment(Long.parseLong(comment));
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        if ("newsInfo".equals(parser.getName())){
                            newsInfos.add(newsInfo);
                            newsInfo=null;
                        }
                        break;
                }
                type=parser.next();
            }
            return newsInfos;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

6.配置服务器:
由于需要从服务器上下载一个XML,因此需要开启Tomcat服务器。在Tomcat根目录下找到bin文件夹,运行该文件下的startup.bat文件开启服务器,可在cmd下输入ipconfig来查看。然后在Tomcat的安装目录打开webapps文件夹,将NewsInfo.json文件放置在ROOT文件夹下。NewsInfo.json的代码如下:

[
  {
    "icon": "http://10.3.24.180:8080/images/a.PNG",
    "title": "科技温暖世界",
    "content": "进入一个更有爱的领域",
    "type": "1",
    "comment": "69"
  },
  {
    "icon": "http://10.3.24.180:8080/images/b.PNG",
    "title": "《神武》",
    "content": "新美术资源盘点,视觉新体验",
    "type": "2",
    "comment": "35"
  },
  {
    "icon": "http://10.3.24.180:8080/images/c.PNG",
    "title": "南北车正式公布合并",
    "content": "南北车将于今日正式公布合并",
    "type": "3",
    "comment": "2"
  },
  {
    "icon": "http://10.3.24.180:8080/images/d.PNG",
    "title": "萌呆了!汪星人抱玩偶酣睡",
    "content": "汪星人抱玩偶酣睡,萌翻网友",
    "type": "1",
    "comment": "25"
  },
  {
    "icon": "http://10.3.24.180:8080/images/e.PNG",
    "title": "风力发电进校园",
    "content": "风力发电普进校园",
    "type": "2",
    "comment": "26"
  },
  {
    "icon": "http://10.3.24.180:8080/images/f.PNG",
    "title": "地球一小时",
    "content": "地球熄灯一小时",
    "type": "1",
    "comment": "23"
  },
  {
    "icon": "http://10.3.24.180:8080/images/g.PNG",
    "title": "最美公路",
    "content": "最美公路,难以想象",
    "type": "1",
    "comment": "23"
  }
]

上述代码标签为的值代表图片的地址因此需要在ROOT目录下创建一个img的文件夹,放置相应的图片。
7.在AndroidMainFest.xml里面配置相应的权限:

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

三.运行结果如下:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值