要实现一个横向矩形评论栏,可以使用Android的LinearLayout布局和RecyclerView来实现。下面是一个简单的示例代码:
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private CommentAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
// 假设有一个包含评论数据的List
List comments = new ArrayList<>();
comments.add("评论1");
comments.add("评论2");
comments.add("评论3");
adapter = new CommentAdapter(comments);
recyclerView.setAdapter(adapter);
}
}
public class CommentAdapter extends RecyclerView.Adapter {
private List comments;
public CommentAdapter(List comments) {
this.comments = comments;
}
@NonNull
@Override
public CommentViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.item_comment, parent, false);
return new CommentViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull CommentViewHolder holder, int position) {
String comment = comments.get(position);
holder.commentTextView.setText(comment);
}
@Override
public int getItemCount() {
return comments.size();
}
public class CommentViewHolder extends RecyclerView.ViewHolder {
TextView commentTextView;
public CommentViewHolder(@NonNull View itemView) {
super(itemView);
commentTextView = itemView.findViewById(R.id.commentTextView);
}
}
}
item_comment.xml
的布局文件,用于定义RecyclerView的每个评论项的布局:
在上述代码中,使用LinearLayout作为外部容器,并将RecyclerView设置为水平方向布局。然后使用CommentAdapter将评论数据绑定到RecyclerView的每个项上,并定义了一个简单的item_comment布局文件来显示每个评论项。