android 消息机制与仿新闻客户端
效果图如下:
具体步骤如下:
1 布局文件中控件的设计
2 访问远程服务器的资源xml文件,该文件包含新闻的内容等信息
3 访问到内容后把访问内容显示到页面上
具体代码如下:
1 MainActivity
packagecom.yuanlp.newsclient;importandroid.graphics.Color;importandroid.os.Bundle;importandroid.os.Handler;importandroid.os.Message;importandroid.support.v7.app.AppCompatActivity;importandroid.view.View;importandroid.view.ViewGroup;importandroid.widget.BaseAdapter;importandroid.widget.LinearLayout;importandroid.widget.ListView;importandroid.widget.TextView;importandroid.widget.Toast;importcom.yuanlp.newsclient.bean.NewsBean;importcom.yuanlp.newsclient.utils.XMLToBean;importcom.yuanlp.newsclient.view.SmartImageView;importjava.io.InputStream;importjava.net.HttpURLConnection;importjava.net.URL;importjava.util.List;publicclassMainActivityextendsAppCompatActivity{privatestaticfinalintLOAD_ERROR=2;privatestaticfinalintLOAD_SUCCESS=1;privateListViewmLv_news;privateLinearLayoutmLoading;//new一个Handler来做android的消息机制,处理子线程数据privateHandlerhandler=newHandler(){@OverridepublicvoidhandleMessage(Messagemsg){//不管加载成功失败,进度条应该隐藏mLoading.setVisibility(View.INVISIBLE);switch(msg.what){caseLOAD_ERROR:Toast.makeText(MainActivity.this,"加载失败",Toast.LENGTH_SHORT).show();break;caseLOAD_SUCCESS://显示listView的内容mLv_news.setAdapter(newMyNewsAdapter());break;}}};privateList<NewsBean>mList;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);/***初始化获取界面元素*/initView();/***加载远程资源到本地文件*/loadMessage();//readMessage();}/***初始化界面*/privatevoidinitView(){setContentView(R.layout.activity_main);mLv_news=(ListView)findViewById(R.id.lv_news);mLoading=(LinearLayout)findViewById(R.id.ll_loading);//打开客户端后,设置ll_loading可见mLoading.setVisibility(View.VISIBLE);}/***加载远程资源到本地*/privatevoidloadMessage(){NewsBeannewsBean=null;//访问网络不能再主线程中进行,需要一个新线程newThread(){@Overridepublicvoidrun(){try{Thread.sleep(5000);NewsBeannewsBean=null;URLurl=newURL("http://192.168.1.107:8080/WebServer/news.xml");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestMethod("GET");intcode=conn.getResponseCode();if(code==200){//获取到资源InputStreamis=conn.getInputStream();//调用utils方法,将xml文件转为list类型返回mList=XMLToBean.readStream(newsBean,is);//利用android的循环消息机制,放到UI线程中执行结果Messagemsg=Message.obtain();msg.what=LOAD_SUCCESS;handler.sendMessage(msg);}else{Messagemsg=Message.obtain();msg.what=LOAD_ERROR;handler.sendMessage(msg);}}catch(Exceptione){e.printStackTrace();Messagemsg=Message.obtain();msg.what=LOAD_ERROR;handler.sendMessage(msg);}}}.start();}/***显示listView中的数据*/privateclassMyNewsAdapterextendsBaseAdapter{@OverridepublicintgetCount(){returnmList.size();}@OverridepublicViewgetView(intposition,ViewconvertView,ViewGroupparent){//布局打气筒,把xml资源文件转变为view即加载另外的一个布局文件Viewview=View.inflate(MainActivity.this,R.layout.news,null);//获取子布局文件中的各个控件SmartImageViewimg=(SmartImageView)view.findViewById(R.id.iv_img);TextViewtv_title=(TextView)view.findViewById(R.id.tv_title);TextViewtv_desc=(TextView)view.findViewById(R.id.tv_desc);TextViewtv_type=(TextView)view.findViewById(R.id.tv_type);//获取当前位置的对象NewsBeanitem=getItem(position);//设置图片显示img.showImgByPath(item.getImg());tv_title.setText(item.getTitle());tv_desc.setText(item.getDescription());Stringtype=item.getType();if("1".equals(type)){//当类型为1时,表示有评论,而且显示评论数tv_type.setText("评论:"+item.getComment());tv_type.setTextColor(Color.BLACK);tv_type.setBackgroundColor(Color.TRANSPARENT);}elseif("2".equals(type)){tv_type.setText("专题");tv_type.setBackgroundColor(Color.RED);tv_type.setTextColor(Color.WHITE);}elseif("3".equals(type)){tv_type.setText("直播");tv_type.setBackgroundColor(Color.RED);tv_type.setTextColor(Color.WHITE);}returnview;}@OverridepublicNewsBeangetItem(intposition){returnmList.get(position);}@OverridepubliclonggetItemId(intposition){returnposition;}}}
2 utils 中的将xml转为list,可以参考前面几天写的博客,android解析xml。
packagecom.yuanlp.newsclient.utils;importandroid.util.Xml;importcom.yuanlp.newsclient.bean.NewsBean;importorg.xmlpull.v1.XmlPullParser;importjava.io.InputStream;importjava.util.ArrayList;importjava.util.List;/***Createdby原立鹏on2017/6/21.*/publicclassXMLToBean{publicstaticList<NewsBean>readStream(NewsBeannewsBean,InputStreamis){List<NewsBean>list=null;try{XmlPullParserxmlPullParser=Xml.newPullParser();xmlPullParser.setInput(is,"utf-8");intevent=xmlPullParser.getEventType();while(event!=XmlPullParser.END_DOCUMENT){switch(event){//根据eventType来区分,分为START_DOCUMENT,START_TAG,END_TAG,END_DOCUMENTcaseXmlPullParser.START_DOCUMENT:list=newArrayList<NewsBean>();break;caseXmlPullParser.START_TAG:StringtagName=xmlPullParser.getName();//获取标签名称if(tagName.equalsIgnoreCase("item")){newsBean=newNewsBean();}elseif(tagName.equalsIgnoreCase("title")){newsBean.setTitle(xmlPullParser.nextText());}elseif(tagName.equalsIgnoreCase("description")){newsBean.setDescription(xmlPullParser.nextText());}elseif(tagName.equalsIgnoreCase("p_w_picpath")){newsBean.setImg(xmlPullParser.nextText());}elseif(tagName.equalsIgnoreCase("type")){newsBean.setType(xmlPullParser.nextText());}elseif(tagName.equalsIgnoreCase("comment")){newsBean.setComment(xmlPullParser.nextText());}break;caseXmlPullParser.END_TAG:if(xmlPullParser.getName().equalsIgnoreCase("item")&&newsBean!=null){list.add(newsBean);newsBean=null;}}event=xmlPullParser.next();}}catch(Exceptione){e.printStackTrace();}returnlist;}}
3 获取远程新闻的方法
packagecom.yuanlp.newsclient.view;importandroid.content.Context;importandroid.graphics.Bitmap;importandroid.graphics.BitmapFactory;importandroid.os.Handler;importandroid.os.Message;importandroid.support.annotation.Nullable;importandroid.util.AttributeSet;importandroid.widget.ImageView;importjava.io.InputStream;importjava.net.HttpURLConnection;importjava.net.URL;/***Createdby原立鹏on2017/6/21.*//***根据url地址去获取远程图片,并显示到新闻标题的左侧*/publicclassSmartImageViewextendsImageView{privateHandlerhandler=newHandler(){@OverridepublicvoidhandleMessage(Messagemsg){Bitmapbitmap=(Bitmap)msg.obj;setImageBitmap(bitmap);}};publicSmartImageView(Contextcontext){super(context);}publicSmartImageView(Contextcontext,@NullableAttributeSetattrs){super(context,attrs);}publicSmartImageView(Contextcontext,@NullableAttributeSetattrs,intdefStyleAttr){super(context,attrs,defStyleAttr);}publicvoidshowImgByPath(finalStringimgURL){newThread(){@Overridepublicvoidrun(){try{URLurl=newURL(imgURL);HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestMethod("GET");intcode=conn.getResponseCode();if(code==200){InputStreamis=conn.getInputStream();Bitmapbitmap=BitmapFactory.decodeStream(is);Messagemsg=Message.obtain();msg.what=1;msg.obj=bitmap;handler.sendMessage(msg);}}catch(Exceptione){e.printStackTrace();}}}.start();}}
4 activity_main.xml
<?xmlversion="1.0"encoding="utf-8"?><RelativeLayoutxmlns: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"><LinearLayoutandroid:id="@+id/ll_loading"android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center"android:orientation="vertical"android:visibility="invisible"><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:text="TextView"tools:text="正在拼命加载"/><ProgressBarandroid:id="@+id/progressBar"android:layout_width="wrap_content"android:layout_height="wrap_content"/></LinearLayout><ListViewandroid:id="@+id/lv_news"android:layout_width="match_parent"android:layout_height="match_parent"/></RelativeLayout>
5 news.xml
<?xmlversion="1.0"encoding="utf-8"?><RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"><com.yuanlp.newsclient.view.SmartImageViewandroid:id="@+id/iv_img"android:layout_width="72dp"android:layout_height="50dp"android:layout_alignParentLeft="true"android:layout_alignParentStart="true"android:layout_alignParentTop="true"android:layout_marginLeft="3dp"app:srcCompat="@mipmap/ic_launcher"/><TextViewandroid:id="@+id/tv_title"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="3dp"android:layout_marginTop="5dp"android:layout_toRightOf="@+id/iv_img"android:text="新闻标题"/><TextViewandroid:id="@+id/tv_desc"android:layout_width="300dp"android:layout_height="wrap_content"android:layout_below="@+id/tv_title"android:layout_toRightOf="@+id/iv_img"android:ellipsize="end"android:lines="2"android:text="TextView"android:textColor="#99000000"android:textSize="12sp"tools:text="新闻描述新闻描述新闻描述新闻描述新闻描述新闻描述新闻描述新闻描述新闻描述新闻描述新闻描述新闻描述新闻描述新闻描述"/><TextViewandroid:id="@+id/tv_type"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="新闻类型"android:layout_below="@+id/tv_desc"android:layout_alignParentRight="true"android:textSize="10sp"android:textColor="#99000000"/></RelativeLayout>
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。