You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android:ListView选中项传递至另一Activity的ListView问题排查

Hey there! Let's get this sorted out. You're trying to pass only the selected ListView items to another Activity, but right now all items are being sent instead. Let's break down the fixes needed and walk through the corrected code.

Key Issues in Your Current Code

  • Reversed Selection Logic: You're collecting data from unselected items (in the else block) instead of the checked ones.
  • Redundant Intent Extra Calls: You're setting Intent extras inside the loop, which overwrites the values every iteration—this should happen after you've collected all selected data.
  • Target Activity Doesn't Handle Multiple Items: Your FinalCSS Activity is just creating duplicate Team objects instead of processing each selected item you pass over.

Fixed Code for Source Activity (CSS.java)

First, let's fix the selection logic and Intent handling:

// Inside your button click listener
practiceFinal.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // Initialize variables to collect selected data (use StringBuilder for efficient concatenation)
        StringBuilder entry = new StringBuilder();
        StringBuilder judge = new StringBuilder();
        int points = 0;
        int work = 0;
        int design = 0;
        int doc = 0;
        int pres = 0;
        int safety = 0;
        int diff = 0;
        StringBuilder ribbon = new StringBuilder();

        Intent intent = new Intent(CSS.this, FinalCSS.class);
        List<Team> selectedTeams = new ArrayList<>();

        // Loop through teams and collect ONLY selected ones
        for (Team hold : adapterTwo.getTeamArrayList()) {
            if (hold.isChecked()) {
                selectedTeams.add(hold);
                // Add separators to avoid messy concatenation
                if (entry.length() > 0) entry.append(", ");
                entry.append(hold.getEntryNumber());
                
                if (judge.length() > 0) judge.append(", ");
                judge.append(hold.getTeamJudgeNumber());
                
                points += hold.getTotalPoints();
                work += hold.getWorkmanship();
                design += hold.getDesign();
                doc += hold.getDocumnetation();
                pres += hold.getPresentation();
                safety += hold.getSafety();
                diff += hold.getDifficulty();
                
                if (ribbon.length() > 0) ribbon.append(", ");
                ribbon.append(hold.getRibbon());
            }
        }

        // Set Intent extras AFTER collecting all data (no more overwriting!)
        intent.putExtra("KeyEntry", entry.toString());
        intent.putExtra("KeyJudge", judge.toString());
        intent.putExtra("KeyPoints", points);
        intent.putExtra("KeyWork", work);
        intent.putExtra("KeyDesign", design);
        intent.putExtra("KeyDoc", doc);
        intent.putExtra("KeyPres", pres);
        intent.putExtra("KeySafety", safety);
        intent.putExtra("KeyRibbon", ribbon.toString());
        intent.putExtra("KeyDiff", diff);
        
        // Optional cleaner approach: Pass the entire list of selected teams (requires Team to implement Serializable)
        intent.putExtra("SelectedTeams", (Serializable) selectedTeams);

        startActivity(intent);
    }
});

Quick Notes for the Source Activity:

  • Switched to StringBuilder instead of raw String concatenation for better performance with multiple items.
  • Added , separators so multiple entries don't merge into a single unreadable string.
  • Moved all intent.putExtra() calls outside the loop to prevent overwriting values.
  • To use the optional full list pass, update your Team class to implement Serializable:
    public class Team implements Serializable {
        // Your existing fields, constructors, and methods here
    }
    

Fixed Code for Target Activity (FinalCSS.java)

Now let's update the target Activity to properly display the selected items. Using the full SelectedTeams list makes this much cleaner:

listView = findViewById(R.id.listViewFinal);
teamsList = new ArrayList<>();

// Get the full list of selected teams from the Intent
List<Team> selectedTeams = (List<Team>) getIntent().getSerializableExtra("SelectedTeams");

if (selectedTeams != null && !selectedTeams.isEmpty()) {
    // Add all selected teams directly to your list
    teamsList.addAll(selectedTeams);
} else {
    // Fallback: Use individual extras if you didn't pass the full list
    String entry = getIntent().getStringExtra("KeyEntry");
    String judge = getIntent().getStringExtra("KeyJudge");
    Integer points = getIntent().getIntExtra("KeyPoints", 0);
    Integer workmanship = getIntent().getIntExtra("KeyWork", 0);
    Integer design = getIntent().getIntExtra("KeyDesign", 0);
    Integer documentation = getIntent().getIntExtra("KeyDoc", 0);
    Integer pres = getIntent().getIntExtra("KeyPres", 0);
    Integer difficulty = getIntent().getIntExtra("KeyDiff", 0);
    Integer safety = getIntent().getIntExtra("KeySafety", 0);
    String ribbon = getIntent().getStringExtra("KeyRibbon");
    
    // Only add a team if there's valid data
    if (entry != null && !entry.isEmpty()) {
        Team team = new Team(judge, entry, points, workmanship, design, documentation, pres, difficulty, safety, ribbon, true);
        teamsList.add(team);
    }
}

// Set up the adapter with the selected teams
TeamAdapterTwo adapterTwo = new TeamAdapterTwo(FinalCSS.this, teamsList);
listView.setAdapter(adapterTwo);

Quick Notes for the Target Activity:

  • Uses the full SelectedTeams list first (the cleanest approach) if it's available.
  • Removed the duplicate Team object creation that was cluttering your original code.
  • Added a fallback for cases where you might not pass the full list.

内容的提问来源于stack exchange,提问作者mar_speare_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 21:07:51