安卓Andriod使用入门(二十五)【爬新闻】

时间:2021-12-25 01:22:40

读书多了,容颜自然改变。许多时候,自己可能以为许多看过的书籍都成过眼烟云,不复记忆,其实他们仍是潜在的。在气质里,在谈吐上,在胸襟的无涯。当然,也能显露在生活和文字中。


MyAdapter.java代码:

package siso.jsoupnews.adapter;


import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;
import siso.jsoupnews.MessageActivity;
import siso.jsoupnews.R;
import siso.jsoupnews.domain.Message;

/*
* 我的新闻ListView的adapter。
* */


public class MyAdapter extends BaseAdapter {

private List<Message> messages;//ListView显示的数据

private int resource;//显示列表项的Layout

private LayoutInflater inflater;//界面生成器

private Context context;//


public MyAdapter(List<Message> messages, int resource, Context context) {

this.messages = messages;

this.resource = resource;

this.context = context;

inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

}


@Override
public int getCount() {

return messages.size();

}


@Override
public Object getItem(int arg0) {

return messages.get(arg0);

}


@Override
public long getItemId(int arg0) {

return arg0;

}


@Override
public View getView(int arg0, View arg1, ViewGroup arg2) {

if (arg1 == null) {

arg1 = inflater.inflate(resource, null);

}

final Message message = messages.get(arg0);

ImageView img = (ImageView) arg1.findViewById(R.id.img);

//设置ListView中的Item中的TextView

img.setImageResource(message.getImg());

//为TextView设置监听器

img.setOnClickListener(new OnClickListener() {


@Override

public void onClick(View arg0) {

Toast.makeText(context, message.getImg(), Toast.LENGTH_LONG).show();

}

});

TextView title = (TextView) arg1.findViewById(R.id.title);

title.setText(message.getTitle());

title.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// Uri uri = Uri.parse("http://www.baidu.com");
// Intent it = new Intent(Intent.ACTION_VIEW,uri);
// context.startActivity(it);//打开新闻页面
context.startActivity(new Intent(context, MessageActivity.class).putExtra("url", message.getUrl()));//putExtra("url", message.getUrl()) 将MessageActivity中url 对应替换成message中的url
// Toast.makeText(context, message.getTitle(), Toast.LENGTH_LONG).show();

}

});

TextView points = (TextView) arg1.findViewById(R.id.points);

points.setText(message.getPoints());

points.setOnClickListener(new OnClickListener() {


@Override

public void onClick(View arg0) {

Toast.makeText(context, message.getPoints(), Toast.LENGTH_LONG).show();

}

});

TextView time = (TextView) arg1.findViewById(R.id.time);

time.setText(message.getTime());

time.setOnClickListener(new OnClickListener() {


@Override

public void onClick(View arg0) {

Toast.makeText(context, message.getTime(), Toast.LENGTH_LONG).show();

}

});

TextView comments = (TextView) arg1.findViewById(R.id.comments);

comments.setText(message.getComments());

comments.setOnClickListener(new OnClickListener() {


@Override

public void onClick(View arg0) {

Toast.makeText(context, message.getComments(), Toast.LENGTH_LONG).show();

}

});

return arg1;

}


}

Message.java代码:

package siso.jsoupnews.domain;

public class Message {

private int img;//goodBarcode
private String title;//goodName 新闻标题
private String points;//goodProvider 新闻点击数
private String time;//新闻发布时间
private String comments;//新闻评论数



private String url;//新闻地址

public int getImg() {
return img;
}

public void setImg(int img) {
this.img = img;
}

public String getTitle() {
return title;
}

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


public String getPoints() {
return points;
}

public void setPoints(String points) {
this.points = points;
}

public String getComments() {
return comments;
}

public void setComments(String comments) {
this.comments = comments;
}

public String getTime() {
return time;
}

public void setTime(String time) {
this.time = time;
}
public String getUrl() {
return url;
}

public void setUrl(String url) {
this.url = url;
}
public Message(int img, String title, String points, String time, String comments,String url) {

this.img = img;

this.title = title;

this.points = points;

this.time = time;

this.comments = comments;

this.url = url;

}

}

MainActivity.java代码:

package siso.jsoupnews;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;


import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import siso.jsoupnews.adapter.MyAdapter;
import siso.jsoupnews.domain.Message;

//jsoup


public class MainActivity extends Activity {
private static final String[] strs2 = new String[30];
private static final String[] link = new String[30];
//定义一个String数组用来显示ListView的内容private ListView lv;/** Called when the activity is first created. */
private ListView listView = null;
private static final int DIALOG_KEY = 0;
private ProgressAsyncTask myTask;
private List<Map<String, String>> messageList = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//进入页面 加载新闻信息
myTask = new ProgressAsyncTask();
myTask.execute();
//点击“更新”按钮时 重新加载新闻信息
Button sync = (Button) findViewById(R.id.id_btn_sync);
sync.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myTask = new ProgressAsyncTask();
myTask.execute();
}
});
}

// 弹出"查看"对话框
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_KEY: {
ProgressDialog dialog = new ProgressDialog(this);
dialog.setMessage("获取数据中 请稍候...");
dialog.setIndeterminate(true);
dialog.setCancelable(true);
return dialog;
}
}
return null;
}


class ProgressAsyncTask extends AsyncTask<Integer, Integer, String> {

ProgressDialog bar;

public ProgressAsyncTask() {
super();

}

/**
* 这里的Integer参数对应AsyncTask中的第一个参数 这里的String返回值对应AsyncTask的第三个参数
* 该方法并不运行在UI线程当中,主要用于异步操作,所有在该方法中不能对UI当中的空间进行设置和修改
* 但是可以调用publish Progress方法触发onProgressUpdate对UI进行操作
*/

@Override
protected String doInBackground(Integer... params) {
try {
Document doc = Jsoup.connect("https://news.ycombinator.com/newest").get();
Elements athings = doc.select("tr.athing");
Elements subtexts = doc.select("td.subtext");
int index = 0;
for (Element athing : athings) {
Map<String, String> messageMap = new HashMap<>();
messageMap.put("rank", athing.getElementsByClass("rank").text());//序号
Element title = athing.select("td.title a").first();
messageMap.put("title", title.text());//新闻标题
messageMap.put("title_href", title.attr("abs:href"));//新闻链接
if (athing.select("td.title a").size()>=2) {
Element sitestr = athing.select("td.title a").get(1);
messageMap.put("sitestr", sitestr.text());//发表网站
messageMap.put("sitestr_href", sitestr.attr("abs:href")); //发表网站链接
}

Element subtext = subtexts.get(index);
if (null != subtext) {
Element score = subtext.select("span.score").first();
messageMap.put("points", score.text());//point数
Element user = subtext.select("a").first();
messageMap.put("user", user.text());//用户
messageMap.put("user_href", user.attr("abs:href"));//用户链接
Element times = subtext.select("a").get(1);
messageMap.put("times", times.text());//发表时间
Element comments = subtext.select("a").last();
messageMap.put("comments", comments.text());//评论数
}
index++;
messageList.add(messageMap);
}

} catch (IOException e) {
Toast.makeText(MainActivity.this, "" + "检查网络", Toast.LENGTH_SHORT).show();
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

/**
* 这里的String参数对应AsyncTask中的第三个参数(也就是接收doInBackground的返回值)
* 在doInBackground方法执行结束之后在运行,并且运行在UI线程当中 可以对UI空间进行设置
*/

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
bar.dismiss();
// 获得ListView句柄
listView = (ListView) findViewById(R.id.listView);
final MyAdapter mgs = new MyAdapter(getListData(), R.layout.item, MainActivity.this);

listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//int position =Integer.parseInt(arg1.getTag().toString());
mgs.getView(arg2, arg1, listView);
}

});

listView.setAdapter(mgs);
}

/*ListView数据*/
private List<Message> getListData() {
List<Message> list = new ArrayList<Message>();
for (Map<String, String> messageMap : messageList) {
Message message = new Message(R.drawable.icon, messageMap.get("rank")+messageMap.get("title"),messageMap.get("points") +" by "+messageMap.get("user"),messageMap.get("times"), messageMap.get("comments"), messageMap.get("title_href"));
list.add(message);
}

return list;
}

// 该方法运行在UI线程当中,并且运行在UI线程当中 可以对UI空间进行设置
@Override
protected void onPreExecute() {
bar = new ProgressDialog(MainActivity.this);
bar.setMessage("正在加载数据····");
bar.setIndeterminate(false);
bar.setCancelable(false);
bar.show();
}

/**
* 这里的Intege参数对应AsyncTask中的第二个参数
* 在doInBackground方法当中,,每次调用publishProgress方法都会触发onProgressUpdate执行
* onProgressUpdate是在UI线程中执行,所有可以对UI空间进行操作
*/

@Override
protected void onProgressUpdate(Integer... values) {
Log.d("onProgressUpdate", "abc");
}
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

//menu操作控制
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (item.getItemId()) {
case R.id.action_about:
Toast.makeText(MainActivity.this, "" + "关于", Toast.LENGTH_SHORT).show();
break;
case R.id.action_settings:

Toast.makeText(MainActivity.this, "" + "设置", Toast.LENGTH_SHORT).show();
break;
case R.id.action_quit:

Toast.makeText(MainActivity.this, "" + "退出", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}

//格式化输出 当标题长度超过width时 截取前width个字
private static String trim(String s, int width) {
if (s.length() > width)
return s.substring(0, width - 1) + "..";
else
return s;
}
}

MessageActivity.java代码:

package siso.jsoupnews;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MessageActivity extends Activity {
private WebView webView;
private String url;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
webView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);//设置可读取JavaScript网页
webSettings.setAllowFileAccess(true);//可读取文件
webSettings.setBuiltInZoomControls(true);
// webView.loadUrl("http://blog.csdn.net/qq_29407877");//要跳转的网页地址
url=getIntent().getStringExtra("url");
webView.loadUrl(url);//要跳转的网页地址
webView.setWebViewClient(new WebViewClient());
}

private class webViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}

activity_main.xml内容:

<RelativeLayout xmlns: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" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listView"
android:layout_centerHorizontal="true"
android:textColor="@drawable/itemcolor"
/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="更新"
android:id="@+id/id_btn_sync"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_above="@id/listView"/>
</RelativeLayout>

activity_message.xml内容:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical">

<WebView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/webview">


</WebView>
</LinearLayout>

item.xml内容:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="50dp"
android:paddingLeft="2dp" android:paddingRight="2dp">

<ImageView
android:id="@+id/img"
android:layout_height="fill_parent"
android:layout_width="20dp"
android:layout_alignParentLeft="true" />

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_height="fill_parent"
android:layout_width="fill_parent" android:layout_toRightOf="@id/img"
android:paddingLeft="2dp">

<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="18dp" />

<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<TextView
android:id="@+id/points"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#cbcaca"
android:paddingRight="5dp"
android:textSize="14dp"
android:clickable="true"
/>

<TextView
android:id="@+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#cbcaca"
android:textSize="12dp"
android:clickable="true"
android:layout_toRightOf="@id/points"/>

<TextView
android:id="@+id/padding"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#cbcaca"
android:textSize="12dp"
android:text=" | "
android:layout_toRightOf="@id/time"/>

<TextView
android:id="@+id/comments"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#cbcaca"
android:textSize="12dp"
android:paddingLeft="5dp"
android:clickable="true"
android:layout_toRightOf="@id/padding"/>


</RelativeLayout>

</LinearLayout>
<!--<CheckBox-->
<!--android:id="@+id/checked"-->
<!--android:layout_height="fill_parent"-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_alignParentRight="true"-->
<!--android:checked="false"-->
<!--android:focusable="false" />-->
</RelativeLayout>

AndroidManifest.xml内容:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="siso.jsoupnews">


<uses-permission android:name="android.permission.INTERNET"/><!--获取网络权限-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/><!--获 取网络状态权限-->
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">

<activity android:name=".MessageActivity"></activity>
<activity
android:name=".MainActivity"
android:label="@string/app_name" >

<intent-filter>
<action android:name="android.intent.action.MAIN"
android:exported="true"/>


<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- <meta-data android:name="com.google.android.backup.api_key"
android:value="" />-->

</application>

</manifest>

运行结果如图:

安卓Andriod使用入门(二十五)【爬新闻】


安卓Andriod使用入门(二十五)【爬新闻】