要使用RecyclerView實現復雜的ItemList,你需要遵循以下步驟:
build.gradle
文件中,確保已經添加了RecyclerView的依賴項:dependencies {
implementation 'com.android.support:recyclerview-v7:28.0.0'
}
public class User {
private String name;
private String email;
public User(String name, String email) {
this.name = name;
this.email = email;
}
// Getter and Setter methods
}
list_item_user.xml
的文件:<?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="16dp">
<TextView
android:id="@+id/tv_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Name" />
<TextView
android:id="@+id/tv_email"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Email" />
</LinearLayout>
RecyclerView.Adapter
的適配器類,并實現其中的方法。例如,創建一個名為UserAdapter
的類:public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder> {
private List<User> userList;
public UserAdapter(List<User> userList) {
this.userList = userList;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_user, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
User user = userList.get(position);
holder.tvName.setText(user.getName());
holder.tvEmail.setText(user.getEmail());
}
@Override
public int getItemCount() {
return userList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView tvName, tvEmail;
public ViewHolder(View itemView) {
super(itemView);
tvName = itemView.findViewById(R.id.tv_name);
tvEmail = itemView.findViewById(R.id.tv_email);
}
}
}
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
然后,在Activity或Fragment中初始化RecyclerView并設置適配器:
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private UserAdapter adapter;
private List<User> userList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userList = new ArrayList<>();
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
// Add sample data
userList.add(new User("John Doe", "john.doe@example.com"));
userList.add(new User("Jane Smith", "jane.smith@example.com"));
adapter = new UserAdapter(userList);
recyclerView.setAdapter(adapter);
}
}
現在,你已經成功地使用RecyclerView實現了一個復雜的ItemList。你可以根據需要自定義列表項布局和適配器,以滿足你的需求。