首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android GridView 點擊 Item 動態添加到另一 GridView:Adapter 數據源操作

     編輯:程式設計綜合問答

場景

  • 下方 GridView(源):展示所有 App 列表。
  • 上方 GridView(目標):用戶選中的 App,最後保留一個「+」添加按鈕項。
  • 點擊下方 Item → 移動到上方 GridView 末尾(+ 按鈕前)。

核心思路:操作 Adapter 數據源 + notifyDataSetChanged

// 1. 兩個 GridView 共用或各自有 Adapter
// 源 GridView
GridView gvSource = findViewById(R.id.gv_source);
AppAdapter sourceAdapter = new AppAdapter(this, allApps);
gvSource.setAdapter(sourceAdapter);

// 目標 GridView(含固定「+」項)
List<AppInfo> targetList = new ArrayList<>();
targetList.add(new AppInfo("ADD_BUTTON", "+"));  // 佔位符
AppAdapter targetAdapter = new AppAdapter(this, targetList);
GridView gvTarget = findViewById(R.id.gv_target);
gvTarget.setAdapter(targetAdapter);

// 2. 源 GridView 項目點擊監聽
gvSource.setOnItemClickListener((parent, view, position, id) -> {
    AppInfo clickedApp = sourceAdapter.getItem(position);
    
    // 3. 目標列表插入到「+」按鈕之前(索引 size-1)
    targetList.add(targetList.size() - 1, clickedApp);
    
    // 4. 可選:從源列表移除(視業務而定)
    // sourceAdapter.remove(clickedApp);
    
    // 5. 刷新目標 GridView
    targetAdapter.notifyDataSetChanged();
});

Adapter 關鍵實現

class AppAdapter extends BaseAdapter {
    Context ctx;
    List<AppInfo> data;
    // 構造、getCount、getItem、getItemId...

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        AppInfo item = data.get(position);
        if ("ADD_BUTTON".equals(item.packageName)) {
            // 渲染「+」按鈕佈局
            return inflater.inflate(R.layout.item_add_button, parent, false);
        }
        // 渲染普通 App 項
        ViewHolder holder;
        if (convertView == null) { ... }
        holder.icon.setImageDrawable(item.icon);
        holder.name.setText(item.name);
        return convertView;
    }
}

關鍵點

  • **操作數據源列表**,而非直接操作 View。
  • 目標列表保留「+」佔位符,插入位置固定為 size()-1。
  • notifyDataSetChanged() 觸發 UI 刷新。
  • 若需從源列表移除,同步調用 sourceAdapter.remove() 並 notifyDataSetChanged()。

總結

GridView 項目互傳 = **兩個 Adapter 各自維護 List 數據源**,點擊事件中操作目標 List 插入/刪除,然後 notifyDataSetChanged()。「+」按鈕作為特殊數據項固定在目標 List 末尾,插入邏輯永遠在它之前。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved