用Android编写新闻列表

时间: 2024-02-10 11:02:52 浏览: 37
编写新闻列表的过程大致如下: 1. 定义数据模型:首先需要定义一个News类,包含新闻的标题、内容、发布时间等信息。 2. 获取数据:从网络或本地数据库中获取新闻数据。网络数据可以使用Android自带的HttpURLConnection或第三方库如OkHttp进行请求,本地数据库可以使用SQLite。 3. 创建列表视图:使用Android提供的RecyclerView控件来展示新闻列表,并创建一个ViewHolder来显示每个新闻项的视图。 4. 绑定数据:将数据绑定到ViewHolder中,更新新闻项的视图。 5. 实现点击事件:为每个新闻项添加点击事件,跳转到新闻详情页。 具体实现过程如下: 1. 定义News类 ```java public class News { private String title; private String content; private String time; public News(String title, String content, String time) { this.title = title; this.content = content; this.time = time; } public String getTitle() { return title; } public String getContent() { return content; } public String getTime() { return time; } } ``` 2. 获取数据 网络请求: ```java public class NewsApi { private static final String TAG = "NewsApi"; private static final String BASE_URL = "https://newsapi.org/v2/"; private static final String API_KEY = "YOUR_API_KEY"; public static List<News> getNews() throws IOException, JSONException { String urlString = BASE_URL + "top-headlines?country=us&apiKey=" + API_KEY; URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); InputStream inputStream = connection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); StringBuffer stringBuffer = new StringBuffer(); String line; while ((line = bufferedReader.readLine()) != null) { stringBuffer.append(line); } String responseString = stringBuffer.toString(); JSONObject responseJson = new JSONObject(responseString); JSONArray articles = responseJson.getJSONArray("articles"); List<News> newsList = new ArrayList<>(); for (int i = 0; i < articles.length(); i++) { JSONObject article = articles.getJSONObject(i); String title = article.getString("title"); String content = article.getString("description"); String time = article.getString("publishedAt"); News news = new News(title, content, time); newsList.add(news); } return newsList; } } ``` 本地数据库: ```java public class NewsDbHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "news.db"; private static final int DATABASE_VERSION = 1; private static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + NewsEntry.TABLE_NAME + " (" + NewsEntry._ID + " INTEGER PRIMARY KEY," + NewsEntry.COLUMN_NAME_TITLE + " TEXT," + NewsEntry.COLUMN_NAME_CONTENT + " TEXT," + NewsEntry.COLUMN_NAME_TIME + " TEXT)"; private static final String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + NewsEntry.TABLE_NAME; public NewsDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } public void onCreate(SQLiteDatabase db) { db.execSQL(SQL_CREATE_ENTRIES); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(SQL_DELETE_ENTRIES); onCreate(db); } public void addNews(News news) { SQLiteDatabase db = getWritableDatabase(); ContentValues values = new ContentValues(); values.put(NewsEntry.COLUMN_NAME_TITLE, news.getTitle()); values.put(NewsEntry.COLUMN_NAME_CONTENT, news.getContent()); values.put(NewsEntry.COLUMN_NAME_TIME, news.getTime()); db.insert(NewsEntry.TABLE_NAME, null, values); db.close(); } public List<News> getNews() { SQLiteDatabase db = getReadableDatabase(); String[] projection = { NewsEntry._ID, NewsEntry.COLUMN_NAME_TITLE, NewsEntry.COLUMN_NAME_CONTENT, NewsEntry.COLUMN_NAME_TIME }; Cursor cursor = db.query( NewsEntry.TABLE_NAME, projection, null, null, null, null, null ); List<News> newsList = new ArrayList<>(); while (cursor.moveToNext()) { String title = cursor.getString(cursor.getColumnIndexOrThrow(NewsEntry.COLUMN_NAME_TITLE)); String content = cursor.getString(cursor.getColumnIndexOrThrow(NewsEntry.COLUMN_NAME_CONTENT)); String time = cursor.getString(cursor.getColumnIndexOrThrow(NewsEntry.COLUMN_NAME_TIME)); News news = new News(title, content, time); newsList.add(news); } cursor.close(); db.close(); return newsList; } public static class NewsEntry implements BaseColumns { public static final String TABLE_NAME = "news"; public static final String COLUMN_NAME_TITLE = "title"; public static final String COLUMN_NAME_CONTENT = "content"; public static final String COLUMN_NAME_TIME = "time"; } } ``` 3. 创建列表视图 在布局文件中添加RecyclerView控件: ```xml <androidx.recyclerview.widget.RecyclerView android:id="@+id/recycler_view" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" tools:listitem="@layout/item_news" /> ``` 在Activity中获取RecyclerView并设置Adapter: ```java public class NewsListActivity extends AppCompatActivity { private RecyclerView recyclerView; private NewsAdapter newsAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_news_list); recyclerView = findViewById(R.id.recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(this)); newsAdapter = new NewsAdapter(new ArrayList<>()); recyclerView.setAdapter(newsAdapter); // 获取新闻数据并更新列表 List<News> newsList = getNews(); newsAdapter.updateNews(newsList); } private List<News> getNews() { // 获取新闻数据 return null; } } ``` 4. 绑定数据 创建ViewHolder来显示新闻项的视图: ```java public class NewsViewHolder extends RecyclerView.ViewHolder { private TextView titleTextView; private TextView contentTextView; private TextView timeTextView; public NewsViewHolder(@NonNull View itemView) { super(itemView); titleTextView = itemView.findViewById(R.id.title_text_view); contentTextView = itemView.findViewById(R.id.content_text_view); timeTextView = itemView.findViewById(R.id.time_text_view); } public void bind(News news) { titleTextView.setText(news.getTitle()); contentTextView.setText(news.getContent()); timeTextView.setText(news.getTime()); } } ``` 创建Adapter来管理新闻列表的视图: ```java public class NewsAdapter extends RecyclerView.Adapter<NewsViewHolder> { private List<News> newsList; public NewsAdapter(List<News> newsList) { this.newsList = newsList; } public void updateNews(List<News> newsList) { this.newsList = newsList; notifyDataSetChanged(); } @NonNull @Override public NewsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_news, parent, false); return new NewsViewHolder(itemView); } @Override public void onBindViewHolder(@NonNull NewsViewHolder holder, int position) { News news = newsList.get(position); holder.bind(news); } @Override public int getItemCount() { return newsList.size(); } } ``` 5. 实现点击事件 在ViewHolder中为新闻项添加点击事件: ```java public class NewsViewHolder extends RecyclerView.ViewHolder { private TextView titleTextView; private TextView contentTextView; private TextView timeTextView; public NewsViewHolder(@NonNull View itemView) { super(itemView); titleTextView = itemView.findViewById(R.id.title_text_view); contentTextView = itemView.findViewById(R.id.content_text_view); timeTextView = itemView.findViewById(R.id.time_text_view); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 跳转到新闻详情页 } }); } public void bind(News news) { titleTextView.setText(news.getTitle()); contentTextView.setText(news.getContent()); timeTextView.setText(news.getTime()); } } ```

相关推荐

最新推荐

recommend-type

tensorflow-2.9.2-cp39-cp39-win-amd64.whl

python爬虫案例
recommend-type

2023年下半年计算机等级考试-公共基础-WPS-PS.zip

2023年下半年计算机等级一级考试Photoshop考点梳理 2023年下半年计算机等级一级考试WPS office考点汇总 2023年下半年计算机二级考试公共基础知识科目考点汇总 根据实际考试情况进行的总结。
recommend-type

Introduction to Data Science Data With R 英文

Introduction to Data Science Data Analysis and Prediction Algorithms with R 英文原版,完整带目录,非常好的数据分析资料,有基于R的完整数据分析过程
recommend-type

数电实验三:74LS151逻辑功能测试、74LS153逻辑功能测试、74LS153全加器、三输入多数表决电路

数电实验三:74LS151逻辑功能测试、74LS153逻辑功能测试、74LS153全加器、三输入多数表决电路
recommend-type

农业机械维修记录(表式).doc

农业机械维修记录(表式).doc
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

MATLAB柱状图在信号处理中的应用:可视化信号特征和频谱分析

![matlab画柱状图](https://img-blog.csdnimg.cn/3f32348f1c9c4481a6f5931993732f97.png) # 1. MATLAB柱状图概述** MATLAB柱状图是一种图形化工具,用于可视化数据中不同类别或组的分布情况。它通过绘制垂直条形来表示每个类别或组中的数据值。柱状图在信号处理中广泛用于可视化信号特征和进行频谱分析。 柱状图的优点在于其简单易懂,能够直观地展示数据分布。在信号处理中,柱状图可以帮助工程师识别信号中的模式、趋势和异常情况,从而为信号分析和处理提供有价值的见解。 # 2. 柱状图在信号处理中的应用 柱状图在信号处理
recommend-type

从键盘输入一段英文字符串,其中包含多个字母‘h',请编写程序利用正则表达式,将英文字符串中的’h'全部改为‘H’

好的,我可以帮您解决这个问题。 您可以使用 Python 编写一个程序来实现这个功能。具体步骤如下: 1. 首先导入 re 模块,这个模块是 Python 中用于处理正则表达式的模块。 2. 然后定义一个包含英文字符串的变量,例如: text = "This is a string containing multiple h's." 3. 接下来,使用 re.sub() 方法来进行替换操作。re.sub() 方法的第一个参数是正则表达式,第二个参数是替换的字符或字符串,第三个参数是被替换的字符串。在这个例子里,我们需要将所有的小写字母 h 替换成大写字母 H,所以正则表达式可以写成
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。