请生成一段Android代码 实现 一行一行的新闻布局,要求左边是文字标题,有发表时间,右边是新闻图片。
时间: 2024-04-14 10:28:57 浏览: 60
当然可以!以下是一个简单的Android代码示例,实现了一行一行的新闻布局,左边是文字标题和发表时间,右边是新闻图片。
```java
// 新闻数据模型类
public class News {
private String title;
private String time;
private int image;
public News(String title, String time, int image) {
this.title = title;
this.time = time;
this.image = image;
}
// getter和setter方法省略...
}
// 新闻适配器类
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {
private List<News> newsList;
public NewsAdapter(List<News> newsList) {
this.newsList = newsList;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_news, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
News news = newsList.get(position);
holder.titleTextView.setText(news.getTitle());
holder.timeTextView.setText(news.getTime());
holder.imageView.setImageResource(news.getImage());
}
@Override
public int getItemCount() {
return newsList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView titleTextView;
TextView timeTextView;
ImageView imageView;
public ViewHolder(@NonNull View itemView) {
super(itemView);
titleTextView = itemView.findViewById(R.id.titleTextView);
timeTextView = itemView.findViewById(R.id.timeTextView);
imageView = itemView.findViewById(R.id.imageView);
}
}
}
// 在Activity或Fragment中使用
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private NewsAdapter newsAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
List<News> newsList = new ArrayList<>();
// 添加新闻数据到newsList...
newsAdapter = new NewsAdapter(newsList);
recyclerView.setAdapter(newsAdapter);
}
}
```
以上代码中,我们使用了RecyclerView来展示新闻列表,每个新闻项的布局是通过`item_news.xml`文件定义的。你可以根据实际情况修改布局和适配器中的代码来满足你的需求。
阅读全文