如何在DrawerLayout中实现可横向滑动的可点击卡片?
Hey there! I get it—spending days trying different solutions only to hit errors or crashes is super frustrating. Let's ditch the headache and go with a reliable approach using RecyclerView, which is perfect for creating smooth horizontal swipeable card lists just like Google Play. It's stable, well-documented, and handles click events easily.
Step 1: Update Your Main Layout
First, replace those individual CardView elements in your activity_main.xml with RecyclerView components for each of your two sections (JD Campus and BS Campus). This gives us the horizontal scrolling container we need.
Here's the modified layout code:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context=".MainActivity" tools:openDrawer="start"> <android.support.constraint.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"> <!-- JD Campus Section --> <TextView android:id="@+id/jdCampusText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:layout_marginTop="8dp" android:layout_marginEnd="8dp" android:text="JD Campus" android:textSize="26sp" app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintVertical_bias="0.1"/> <android.support.v7.widget.RecyclerView android:id="@+id/jdCampusRecyclerView" android:layout_width="match_parent" android:layout_height="150dp" android:layout_marginStart="8dp" android:layout_marginTop="8dp" android:layout_marginEnd="8dp" app:layout_constraintTop_toBottomOf="@id/jdCampusText" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"/> <!-- BS Campus Section --> <TextView android:id="@+id/bsCampusText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:layout_marginTop="32dp" android:layout_marginEnd="8dp" android:text="BS Campus" android:textSize="26sp" app:layout_constraintTop_toBottomOf="@id/jdCampusRecyclerView" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"/> <android.support.v7.widget.RecyclerView android:id="@+id/bsCampusRecyclerView" android:layout_width="match_parent" android:layout_height="150dp" android:layout_marginStart="8dp" android:layout_marginTop="8dp" android:layout_marginEnd="8dp" app:layout_constraintTop_toBottomOf="@id/bsCampusText" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"/> </android.support.constraint.ConstraintLayout> </android.support.v4.widget.DrawerLayout>
Step 2: Create a Card Item Layout
Next, make a layout file for individual card items (res/layout/item_card.xml). This is what each swipeable card will look like, using CardView for that rounded corner effect:
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:card_view="http://schemas.android.com/apk/res-auto" android:layout_width="280dp" android:layout_height="match_parent" android:layout_marginEnd="8dp" card_view:cardCornerRadius="4dp" card_view:cardElevation="4dp"> <!-- Add your card content here (text, images, etc.) --> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical"> <TextView android:id="@+id/cardTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Card Title" android:textSize="18sp" android:textStyle="bold"/> <TextView android:id="@+id/cardSubtitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Card Subtitle" android:textSize="14sp" android:layout_marginTop="4dp"/> </LinearLayout> </android.support.v7.widget.CardView>
Step 3: Build the RecyclerView Adapter
Create an adapter class to bind data to the RecyclerView and handle click events. This makes each card interactive:
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.CardViewHolder> { private List<String> cardTitles; private List<String> cardSubtitles; private OnCardClickListener clickListener; // Interface for click events public interface OnCardClickListener { void onCardClick(int position); } public CardAdapter(List<String> titles, List<String> subtitles, OnCardClickListener listener) { this.cardTitles = titles; this.cardSubtitles = subtitles; this.clickListener = listener; } @NonNull @Override public CardViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_card, parent, false); return new CardViewHolder(view); } @Override public void onBindViewHolder(@NonNull CardViewHolder holder, int position) { holder.title.setText(cardTitles.get(position)); holder.subtitle.setText(cardSubtitles.get(position)); // Handle card click holder.itemView.setOnClickListener(v -> clickListener.onCardClick(position)); } @Override public int getItemCount() { return cardTitles.size(); } public static class CardViewHolder extends RecyclerView.ViewHolder { TextView title; TextView subtitle; public CardViewHolder(@NonNull View itemView) { super(itemView); title = itemView.findViewById(R.id.cardTitle); subtitle = itemView.findViewById(R.id.cardSubtitle); } } }
Step 4: Configure RecyclerView in MainActivity
Finally, set up the RecyclerViews in your MainActivity to enable horizontal scrolling and attach the adapter:
public class MainActivity extends AppCompatActivity implements CardAdapter.OnCardClickListener { private RecyclerView jdCampusRecyclerView; private RecyclerView bsCampusRecyclerView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize RecyclerViews jdCampusRecyclerView = findViewById(R.id.jdCampusRecyclerView); bsCampusRecyclerView = findViewById(R.id.bsCampusRecyclerView); // Set horizontal LayoutManager for both LinearLayoutManager jdLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); LinearLayoutManager bsLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); jdCampusRecyclerView.setLayoutManager(jdLayoutManager); bsCampusRecyclerView.setLayoutManager(bsLayoutManager); // Sample data for JD Campus List<String> jdTitles = Arrays.asList("JD Card 1", "JD Card 2", "JD Card 3", "JD Card 4"); List<String> jdSubtitles = Arrays.asList("Subtitle 1", "Subtitle 2", "Subtitle 3", "Subtitle 4"); // Sample data for BS Campus List<String> bsTitles = Arrays.asList("BS Card 1", "BS Card 2", "BS Card 3"); List<String> bsSubtitles = Arrays.asList("BS Subtitle 1", "BS Subtitle 2", "BS Subtitle 3"); // Create and attach adapters CardAdapter jdAdapter = new CardAdapter(jdTitles, jdSubtitles, this); CardAdapter bsAdapter = new CardAdapter(bsTitles, bsSubtitles, this); jdCampusRecyclerView.setAdapter(jdAdapter); bsCampusRecyclerView.setAdapter(bsAdapter); } // Handle card clicks @Override public void onCardClick(int position) { // Add your click logic here (e.g., open a new activity, show a dialog) Toast.makeText(this, "Card clicked at position: " + position, Toast.LENGTH_SHORT).show(); } }
Why This Works
RecyclerViewis Android's official component for scrollable lists, optimized for performance and stability—no random crashes or weird errors like you might get with custom swipe implementations.- The
LinearLayoutManagerset to horizontal gives us the exact swipe behavior you want, matching Google Play's style. - The adapter pattern makes it easy to add/remove cards and handle click events cleanly.
You can customize the card layout, add images, or adjust styling to fit your app's design—this is just a solid starting point that should work without issues.
内容的提问来源于stack exchange,提问作者Jerry Chen

