在Android中,要自定义列表项视图,您需要遵循以下步骤:
list_item_custom.xml
的文件,并在其中添加一个TextView、一个ImageView和一个ProgressBar。<?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="wrap_content"
android:orientation="horizontal"
android:padding="8dp">
<ImageView
android:id="@+id/imageView"
android:layout_width="48dp"
android:layout_height="48dp"
android:src="@drawable/ic_launcher_background" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:text="Title"
android:textSize="16sp" />
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:visibility="gone" />
</LinearLayout>
BaseAdapter
或RecyclerView.Adapter
。在这个例子中,我们将使用RecyclerView.Adapter
。public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
private List<String> dataList;
private Context context;
public CustomAdapter(Context context, List<String> dataList) {
this.context = context;
this.dataList = dataList;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_custom, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.textView.setText(dataList.get(position));
}
@Override
public int getItemCount() {
return dataList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView textView;
public ImageView imageView;
public ProgressBar progressBar;
public ViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.textView);
imageView = itemView.findViewById(R.id.imageView);
progressBar = itemView.findViewById(R.id.progressBar);
}
}
}
RecyclerView
实例,然后设置适配器。public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private CustomAdapter customAdapter;
private List<String> dataList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
dataList = new ArrayList<>();
for (int i = 1; i <= 20; i++) {
dataList.add("Item " + i);
}
customAdapter = new CustomAdapter(this, dataList);
recyclerView.setAdapter(customAdapter);
}
}
这样,您就可以在Android中自定义列表项视图了。根据您的需求,您可以在list_item_custom.xml
文件中添加更多的视图和控件。