1. 程式人生 > >Android實現新聞瀏覽功能

Android實現新聞瀏覽功能

*要求:通過一個案例“新聞客戶端”向大家演示AsyncHttpClient和
SmartImageView的綜合使用。*
1:相關知識
市面上一些常見軟體,例如手機QQ、天貓、京東商場等,都載入了大量網路上的圖片。用Android自帶的API實現這一功能十分麻煩而且耗時。為此,程式設計愛好者開發了一個開源專案——SmartImageView。
– 開源專案SmartImageView的出現主要是為了加速從網路上載入圖片,它繼承自ImageView類,支援根據URL地址載入圖片、支援非同步載入圖片、支援圖片快取等。
2:設計佈局檔案
(1)主介面設計構造

<?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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft
="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.administrator.newsshow.MainActivity">
` <FrameLayout android:layout_width="match_parent" android:layout_height
="match_parent">
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/loading" android:visibility="invisible" android:layout_gravity="center" android:orientation="vertical" > <ProgressBar android:layout_width="wrap_content" android:layout_height="match_parent" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="正在載入資訊.......!" /> </LinearLayout> <ListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/lv_news"></ListView> </FrameLayout> </LinearLayout>

如下圖所示:
這裡寫圖片描述
(2)ListView控制元件子佈局 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="65dip">
    <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:建立JSON檔案,實現一個線上編輯器

[
  {
    "icon": "http://192.168.1.109:8080/images/a.jpg",
    "title": "科技溫暖世界",
    "content": "進入一個更有愛的領域",
    "type": "1",
    "comment": "69"
  },
  {
    "icon": "http://192.168.1.109:8080/images/b.jpg",
    "title": "《神武》",
    "content": "新美術資源盤點,視覺新體驗",
    "type": "2",
    "comment": "35"
  },
  {
    "icon": "http://192.168.1.109:8080/images/c.jpg",
    "title": "南北車正式公佈合併",
    "content": "南北車將於今日正式公佈合併",
    "type": "3",
    "comment": "2"
  },
  {
    "icon": "http://192.168.1.109:8080/images/d.jpg",
    "title": "萌呆了!汪星人抱玩偶酣睡",
    "content": "汪星人抱玩偶酣睡,萌翻網友",
    "type": "1",
    "comment": "25"
  },
  {
    "icon": "http://192.168.1.109:8080/images/e.jpg",
    "title": "風力發電進校園",
    "content": "風力發電普進校園",
    "type": "2",
    "comment": "26"
  },
  {
    "icon": "http://192.168.1.109:8080/images/f.jpg",
    "title": "地球一小時",
    "content": "地球熄燈一小時",
    "type": "1",
    "comment": "23"
  },
  {
    "icon": "http://192.168.1.109:8080/images/g.jpg",
    "title": "最美公路",
    "content": "最美公路,難以想象",
    "type": "1",
    "comment": "23"
  }
]

4:建立實體類

package com.example.administrator.newsshow.entity;

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

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

    public String getTitle() {
        return title;
    }

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

    public String getIconPath() {
        return iconPath;
    }

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

    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;
    }
}

5:Tools包下建立工具類JsonParse負責解析JSON資料


public class JsonParse {
    public  static List<NewsInfo> getNewsInfo(String json){
         Gson gson =new Gson();
         Type listType=new TypeToken<NewsInfo>(){

        }.getType();
        List<NewsInfo> newsInfos=gson.fromJson(json,listType);
        return  newsInfos;
    }

}

6:建立介面卡
adapter包下建立NewsAdapter類

package com.example.administrator.newsshow.adapter;

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

import com.example.administrator.newsshow.R;
import com.example.administrator.newsshow.entity.NewsInfo;
import com.loopj.android.image.SmartImageView;

import java.util.List;

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

public class NewsAdapter  extends ArrayAdapter<NewsInfo>{
      public  NewsAdapter (Context context, List<NewsInfo>objects){
            super(context, R.layout.item,objects);
      }
    public View getView (int position, View convertView , ViewGroup parent){
         NewsInfo newsInfo =getItem(position);
         ViewHolder viewHolder;
        View view=null;
        if(convertView==null){
            view=View.inflate(getContext(),R.layout.item,null);
            viewHolder=new ViewHolder();
            viewHolder.siv=(SmartImageView)view.findViewById(R.id.siv_icon);
            viewHolder.tv_title=(TextView)view.findViewById(R.id.tv_title);
            viewHolder.tv_description=(TextView)view.findViewById(R.id.tv_description);
            viewHolder.tv_type=(TextView)view.findViewById(R.id.tv_type);
            view.setTag(viewHolder);

        }else {
            view =convertView;
            viewHolder=(ViewHolder)view.getTag();
        }
     viewHolder.siv.setImageUrl(newsInfo.getIconPath());
        viewHolder.tv_title.setText(newsInfo.getTitle());
        viewHolder.tv_description.setText(newsInfo.getDescription());
        viewHolder.tv_type.setText(newsInfo.getType()+"");
        return  view;
    }
    class  ViewHolder{
        SmartImageView siv;
    TextView tv_title;
        TextView tv_description;
        TextView tv_type;
    }
}

7:編寫介面互動程式碼
介面邏輯程式碼的設計與實現:

package com.example.administrator.newsshow;

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.example.administrator.newsshow.Tools.JsonParse;
import com.example.administrator.newsshow.adapter.NewsAdapter;
import com.example.administrator.newsshow.entity.NewsInfo;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.image.SmartImageView;

import java.io.UnsupportedEncodingException;
import java.util.List;

import static com.example.administrator.newsshow.R.id.tv_title;

public class MainActivity extends AppCompatActivity {

     private ListView lv_news;
     private LinearLayout loading;
    private List<NewsInfo> newsInfos;

    @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);
        StartExecute();
    }
    private void  StartExecute(){
        System.out.println(">>>>>>>>>>>>>執行了");

        AsyncHttpClient asynchttpClient =new AsyncHttpClient();


        asynchttpClient.get("http://10.2.7.239:8080/NewsInfo.json",new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, org.apache.http.Header[] headers, byte[] bytes) {
                try {
                    String json = new String(bytes, "utf-8");
                    List<NewsInfo> newsInfos = JsonParse.getNewsInfo(json);

                    if (newsInfos == null) {
                        Toast.makeText(MainActivity.this, "解析失敗!", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "獲取成功!", Toast.LENGTH_SHORT).show();
                        loading.setVisibility(View.INVISIBLE);
                        lv_news.setAdapter(new NewsAdapter(MainActivity.this, newsInfos));
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            public void onFailure(int i, org.apache.http.Header[] headers, byte[] bytes, Throwable throwable) {
                System.out.println(">>>>>>>>>獲取失敗!");
            }
            });
    }
}

8:執行結果示意圖如下顯示

這裡寫圖片描述