封装新闻详情内容 News
<span style="font-size:14px;">public class News {
public static interface NewsType {
public static final int TITLE = 1;
public static final int CONTENT = 2;
public static final int IMG = 3;
public static final int DATE = 4;
}
/**
* 标题
*/
private String title;
/**
* 内容
*/
private String content;
/**
* 图片链接
*/
private String imageLink;
/**
* 时间
*/
private int date;
/**
* 类型
*/
private int type;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getImageLink() {
return imageLink;
}
public void setImageLink(String imageLink) {
this.imageLink = imageLink;
this.type = NewsType.IMG;
}
public int getDate(){
return date;
}
public void setDate(int date){
this.date = date;
}
public int getType()
{
return type;
}
public void setType(int type)
{
this.type = type;
}
public String toString(){
return "News [title = "+title+",content = "+content+",imgelink = "+imageLink+",date = "+date+",type = "+type+"]";
}
}
</span>
News的集合NewsDto
public class NewsDto {
private List<News> newses;
private String nextPageUrl ;
public List<News> getNewses()
{
return newses;
}
public void setNewses(List<News> newses)
{
this.newses = newses;
}
public String getNextPageUrl()
{
return nextPageUrl;
}
public void setNextPageUrl(String nextPageUrl)
{
this.nextPageUrl = nextPageUrl;
}
}
在NewsItemBiz添加代码,完成对news的组装,返回一个newsDto。加红的是添加的代码
public class NewsItemBiz {
public NewsItem newsItem;
public List<NewsItem> newsItems = new ArrayList<NewsItem>();
public List<NewsItem> getNewsItems(int newsType, int currentPage)
throws CommonException {
String urlStr = URLUtil.generateUrl(newsType, currentPage);
String htmlStr = DataUtil.doGet(urlStr);
List<NewsItem> newsItems = new ArrayList<NewsItem>();
NewsItem newsItem = null;
Document doc = Jsoup.parse(htmlStr);
Elements units = doc.select("div.news-list>ul>li");
for (int i = 0; i < units.size(); i++) {
newsItem = new NewsItem();
newsItem.setNewsType(newsType);
Element unit_ele = units.get(i);
Element h4_ele = unit_ele.select("div.list-hd>h4").get(0);
Element h4_a_ele = h4_ele.select("a").get(0);
String title = h4_a_ele.text();
String href = h4_a_ele.attr("href");
// Log.e("mao", title);
newsItem.setLink(href);
newsItem.setTitle(title);
Element time = unit_ele.select("a.time").get(0);
String date = time.text();
newsItem.setDate(date);
Element dl_ele = unit_ele.select("span.J_share_title").get(0);// dl
String content = dl_ele.text();
newsItem.setContent(content);
newsItems.add(newsItem);
}
return newsItems;
}
<span style="color:#cc0000;">/**
* 根据文章的url返回一个NewsDto对象
*
* @return
* @throws CommonException
*/
public NewsDto getNews(String urlStr) throws CommonException {
NewsDto newsDto = new NewsDto();
List<News> newses = new ArrayList<News>();
String htmlStr = DataUtil.doGet(urlStr);
Document doc = Jsoup.parse(htmlStr);
// 获得文章中的第一个detail
Element detailEle = doc.select("div.artical-content").get(0);
// 标题
Element titleEle = doc.select("h1.headline").get(0);
News news = new News();
news.setTitle(titleEle.text());
news.setType(NewsType.TITLE);
newses.add(news);
// 内容
Element contentEle = detailEle.select("div.artical-content-read")
.get(0);
Elements childrenEle = contentEle.children();
for (Element child : childrenEle) {
Elements imgEles = child.getElementsByTag("img");
// 图片
if (imgEles.size() > 0) {
for (Element imgEle : imgEles) {
if (imgEle.attr("src").equals(""))//break是结束整个循环体,continue是结束单次循环
continue;
news = new News();
news.setImageLink(imgEle.attr("src"));
newses.add(news);
}
}
// 移除图片
imgEles.remove();
if (child.text().equals(""))
continue;
news = new News();
news.setType(NewsType.CONTENT);
news.setContent(child.outerHtml());
newses.add(news);
}
newsDto.setNewses(newses);
return newsDto;
}</span>
}
在fragment中添加item点击事件,点击转到显示新闻详情的activity并且传递新闻的链接URL
mXListView.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
NewsItem newsItem = mDatas.get(position-1);
Intent intent = new Intent(getActivity(), com.example.mybasketball.activity.NewsContentActivity.class);
intent.putExtra("url", newsItem.getLink());
startActivity(intent);
}
});
显示新闻详情的NewsContentActivity
public class NewsContentActivity extends Activity implements IXListViewLoadMore {
private XListView mListView;
/**
* 该页面的url
*/
private String url;
private com.example.mybasketball.util.NewsItemBiz mNewsItemBiz;
private List<News> mDatas;
private ProgressBar mProgressBar;
private NewContentAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.news_content);
mNewsItemBiz = new NewsItemBiz();
Bundle extras = getIntent().getExtras();
url = extras.getString("url");
mAdapter = new NewContentAdapter(this);
mListView = (XListView) findViewById(R.id.id_listview);
mProgressBar = (ProgressBar) findViewById(R.id.id_newsContentPro);
mListView.setAdapter(mAdapter);
mListView.disablePullRefreash();
mListView.setPullLoadEnable(this);
mListView.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
News news = mDatas.get(position - 1);
String imageLink = news.getImageLink();
//Toast.makeText(NewContentActivity.this, imageLink, 1).show();
Intent intent = new Intent(NewsContentActivity.this,ImageShowActivity.class);
intent.putExtra("url",imageLink);
startActivity(intent);
}
});
mProgressBar.setVisibility(View.VISIBLE);
new LoadDataTask().execute();
}
@Override
public void onLoadMore()
{
}
class LoadDataTask extends AsyncTask<Void, Void, Void>
{
@Override
protected Void doInBackground(Void... params)
{
try
{
mDatas = mNewsItemBiz.getNews(url).getNewses();
} catch (CommonException e)
{
Looper.prepare();
Toast.makeText(getApplicationContext(), e.getMessage(), 1).show();
Looper.loop();
}
return null;
}
@Override
protected void onPostExecute(Void result)
{
if(mDatas == null)
return ;
mAdapter.addList(mDatas);
mAdapter.notifyDataSetChanged();
mProgressBar.setVisibility(View.GONE);
}
}
/**
* 点击返回按钮
* @param view
*/
public void back(View view)
{
finish();
}
}
NewsContentActivity的布局文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/newsContentView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/wangyibg"
android:clickable="true" >
<RelativeLayout
android:id="@+id/head"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<include layout="@layout/news_content_head" />
</RelativeLayout>
<me.maxwin.view.XListView
android:id="@+id/id_listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/head"
android:cacheColorHint="#00000000"
android:divider="@null" />
<ProgressBar
android:id="@+id/id_newsContentPro"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:indeterminateDrawable="@drawable/progressbar_large"
android:visibility="visible" />
<ImageView
android:id="@+id/reLoadImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:clickable="true"
android:src="@drawable/base_empty_view"
android:visibility="invisible" />
</RelativeLayout>
NewContentAdapter显示新闻详情内容的XListView的适配器
public class NewContentAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private List<News> mDatas = new ArrayList<News>();
private ImageLoader imageLoader = ImageLoader.getInstance();
private DisplayImageOptions options;
public NewContentAdapter(Context context) {
mInflater = LayoutInflater.from(context);
imageLoader.init(ImageLoaderConfiguration.createDefault(context));
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.ic_launcher)
.showImageForEmptyUri(R.drawable.ic_launcher)
.showImageOnFail(R.drawable.ic_launcher).cacheInMemory()
.cacheOnDisc().imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565)
.displayer(new FadeInBitmapDisplayer(300)).build();
}
public void addList(List<News> datas) {
mDatas.addAll(datas);
}
@Override
public int getCount() {
return mDatas.size();
}
@Override
public Object getItem(int position) {
return mDatas.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemViewType(int position) {
switch (mDatas.get(position).getType()) {
case NewsType.TITLE:
return 0;
case NewsType.CONTENT:
return 1;
case NewsType.IMG:
return 2;
case NewsType.DATE:
return 3;
}
return -1;
}
@Override
public int getViewTypeCount()
{
return 5;
}
@Override
public boolean isEnabled(int position)
{
switch (mDatas.get(position).getType())
{
case NewsType.IMG:
return true;
default:
return false;
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
News news = mDatas.get(position); // 获取当前项数据
Log.e("xxx", news.toString());
ViewHolder holder = null;
if (null == convertView)
{
holder = new ViewHolder();
switch (news.getType())
{
case NewsType.TITLE:
convertView = mInflater.inflate(R.layout.news_content_title_item, null);
holder.mTextView = (TextView) convertView.findViewById(R.id.text);
break;
case NewsType.CONTENT:
convertView = mInflater.inflate(R.layout.news_content_item, null);
holder.mTextView = (TextView) convertView.findViewById(R.id.text);
break;
case NewsType.IMG:
convertView = mInflater.inflate(R.layout.news_content_img_item, null);
holder.mImageView = (ImageView) convertView.findViewById(R.id.imageView);
break;
case NewsType.DATE:
convertView = mInflater.inflate(R.layout.news_content_bold_title_item, null);
holder.mTextView = (TextView) convertView.findViewById(R.id.text);
break;
}
convertView.setTag(holder);
} else
{
holder = (ViewHolder) convertView.getTag();
}
if (null != news)
{
switch (news.getType())
{
case NewsType.IMG:
imageLoader.displayImage(news.getImageLink(), holder.mImageView, options);
break;
case NewsType.TITLE:
holder.mTextView.setText(news.getTitle());
break;
case NewsType.CONTENT:
holder.mTextView.setText("\u3000\u3000"+Html.fromHtml(news.getContent()));
break;
case NewsType.DATE:
holder.mTextView.setText("\u3000\u3000"+Html.fromHtml(news.getContent()));
default:
// holder.mTextView.setText(Html.fromHtml(item.getContent(),
// null, new MyTagHandler()));
// holder.content.setText(Html.fromHtml("<ul><bold>加粗</bold>sdfsdf<ul>",
// null, new MyTagHandler()));
break;
}
}
return convertView;
}
private final class ViewHolder
{
TextView mTextView;
ImageView mImageView;
}
}
点击图片,显示图片保存的页面ImageShowActivity
public class ImageShowActivity extends Activity {
private String url;
private ProgressBar mLoading;
private GestureImageView mGestureImageView;
private Bitmap mBitmap;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_page);
// 拿到图片的链接
url = getIntent().getExtras().getString("url");
mLoading = (ProgressBar) findViewById(R.id.loading);
mGestureImageView = (GestureImageView) findViewById(R.id.image);
new DownloadImgTask().execute();
}
/**
* 点击返回按钮
*
* @param view
*/
public void back(View view)
{
finish();
}
/**
* 点击下载按钮
*
* @param view
*/
public void downloadImg(View view)
{
mGestureImageView.setDrawingCacheEnabled(true);
if (FileUtil.writeSDcard(url, mGestureImageView.getDrawingCache()))
{
Toast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_SHORT).show();
} else
{
Toast.makeText(getApplicationContext(), "保存失败", Toast.LENGTH_SHORT).show();
}
mGestureImageView.setDrawingCacheEnabled(false);
}
class DownloadImgTask extends AsyncTask<Void, Void, Void>
{
@Override
protected Void doInBackground(Void... params)
{
mBitmap = Http.HttpGetBmp(url);
return null;
}
@Override
protected void onPostExecute(Void result)
{
mGestureImageView.setImageBitmap(mBitmap);
mLoading.setVisibility(View.GONE);
super.onPostExecute(result);
}
}
}
文件储存的工具类FileUtil
public class FileUtil
{
public static String filePath = android.os.Environment.getExternalStorageDirectory() + "/CSDNDownLoad";
public static String getFileName(String str)
{
str = str.replaceAll("(?i)[^a-zA-Z0-9\u4E00-\u9FA5]", "");
System.out.println("filename = " + str);
return str + ".png";
}
public static void writeSDcard(String fileName, InputStream inputStream)
{
try
{
File file = new File(filePath);
if (!file.exists())
{
file.mkdirs();
}
FileOutputStream fileOutputStream = new FileOutputStream(filePath + "/" + fileName);
byte[] buffer = new byte[512];
int count = 0;
while ((count = inputStream.read(buffer)) > 0)
{
fileOutputStream.write(buffer, 0, count);
}
fileOutputStream.flush();
fileOutputStream.close();
inputStream.close();
System.out.println("writeToSD success");
} catch (IOException e)
{
e.printStackTrace();
System.out.println("writeToSD fail");
}
}
public static boolean writeSDcard(String fileName, Bitmap bmp)
{
try
{
File file = new File(filePath);
if (!file.exists())
{
file.mkdirs();
}
File imgFile = new File(filePath + "/" + getFileName(fileName));
if (imgFile.exists())
{
return true;
}
InputStream is = bitmap2InputStream(bmp);
FileOutputStream fileOutputStream = new FileOutputStream(imgFile);
byte[] buffer = new byte[512];
int count = 0;
while ((count = is.read(buffer)) > 0)
{
fileOutputStream.write(buffer, 0, count);
}
fileOutputStream.flush();
fileOutputStream.close();
is.close();
System.out.println("writeToSD success");
} catch (IOException e)
{
e.printStackTrace();
System.out.println("writeToSD fail");
return false;
}
return true;
}
public static byte[] bitmap2Bytes(Bitmap bm)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
public static InputStream bitmap2InputStream(Bitmap bm)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Write a compressed version of the bitmap to the specified
// outputstream.
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
InputStream is = new ByteArrayInputStream(baos.toByteArray());
return is;
}
}
最后别忘了注册activity