androidstudio新闻页面代码
时间: 2024-01-01 12:18:13 浏览: 139
News_AndroidStudio源代码
5星 · 资源好评率100%
以下是一个简单的Android Studio新闻页面代码示例,包含了上述步骤中提到的一些关键代码:
1. 布局文件 "activity_main.xml":
```xml
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/news_list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
2. RecyclerView Adapter "NewsAdapter.java":
```java
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {
private List<News> mNewsList;
static class ViewHolder extends RecyclerView.ViewHolder {
TextView newsTitle;
public ViewHolder(View view) {
super(view);
newsTitle = (TextView) view.findViewById(R.id.news_title);
}
}
public NewsAdapter(List<News> newsList) {
mNewsList = newsList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_item, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
News news = mNewsList.get(position);
holder.newsTitle.setText(news.getTitle());
}
@Override
public int getItemCount() {
return mNewsList.size();
}
}
```
3. RecyclerView Item 布局文件 "news_item.xml":
```xml
<TextView
android:id="@+id/news_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:padding="10dp" />
```
4. MainActivity.java:
```java
public class MainActivity extends AppCompatActivity {
private List<News> mNewsList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initNews();
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.news_list);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
NewsAdapter adapter = new NewsAdapter(mNewsList);
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(new NewsAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
News news = mNewsList.get(position);
Intent intent = new Intent(MainActivity.this, NewsDetailActivity.class);
intent.putExtra("news_url", news.getUrl());
startActivity(intent);
}
});
}
private void initNews() {
// TODO: 使用Retrofit或其他库从后端API获取新闻数据,并添加到mNewsList中
}
}
```
5. 新闻详情页 "NewsDetailActivity.java":
```java
public class NewsDetailActivity extends AppCompatActivity {
private WebView mWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news_detail);
mWebView = (WebView) findViewById(R.id.web_view);
String newsUrl = getIntent().getStringExtra("news_url");
mWebView.loadUrl(newsUrl);
}
}
```
希望这些代码能帮助您构建一个简单的新闻页面!
阅读全文