将一行从一个列表视图发送到另一个列表视图

Posted

技术标签:

【中文标题】将一行从一个列表视图发送到另一个列表视图【英文标题】:send a row from one listview to another listview 【发布时间】:2020-03-28 07:42:31 【问题描述】:

我在同一个活动中有两个列表视图,其中一个有元素,另一个是空的,我想通过长按将任何元素发送到第二个 lisview,我希望元素执行与第一个相同的操作listview(open an activity) 这是我的代码,请告诉我该怎么做:

MainActivity.java


import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;


public class MainActivity extends AppCompatActivity 

    private static final String TAG = "MainActivity";
    DB_Sqlite db = new DB_Sqlite(this);
    ListView listView1;
    ListView listView;



    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         listView = (ListView) findViewById(R.id.list_view);
         listView1 = (ListView) findViewById(R.id.list_view1);

        final ArrayList arrayList = new ArrayList<String>();
        arrayList.add("Complex Complex");
        arrayList.add("Trix Complex");
        arrayList.add("Kingdoms");
        final ArrayList arrayList1 = new ArrayList<String>();
        final ListAdapter adapter = new ArrayAdapter<>(MainActivity.this,android.R.layout.simple_list_item_1,arrayList);
        listView.setAdapter(adapter);




        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() 
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) 
                if (position == 0)
                    Intent intent = new Intent(MainActivity.this,cc.class);
                    startActivity(intent);
                
                if (position == 1)
                    Intent intent = new Intent(MainActivity.this,tc.class);
                    startActivity(intent);
                
                if (position == 2)
                    Intent intent = new Intent(MainActivity.this,k.class);
                    startActivity(intent);
                


            
        );
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() 
    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long l) 
        if (position == 0) 

            Boolean result = db.insertData((String) arrayList.get(position));
            if (result == true)
                Toast.makeText(MainActivity.this,"Added To Favorite",Toast.LENGTH_SHORT).show();
            else
                Toast.makeText(MainActivity.this, "Already Exist", Toast.LENGTH_SHORT).show();
            

        
        if (position == 1)
            Toast.makeText(MainActivity.this, "TC Added to Favorites", Toast.LENGTH_SHORT).show();
        
        if (position == 2)
            Toast.makeText(MainActivity.this, "K Added to Favorites", Toast.LENGTH_SHORT).show();
        
        return true;
    

);



public void showData()
    ArrayList arrayList1 = db.getAllrecord();
    final ListAdapter adapter1 = new ArrayAdapter<>(MainActivity.this,android.R.layout.simple_list_item_1,arrayList1);
    listView1.setAdapter(adapter1);

    

this is what i have done so far please help, thank you very much.
DB_Sqlite.java


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

import java.util.ArrayList;

public class DB_Sqlite extends SQLiteOpenHelper 
    public static final String BDname = "data.db";
    public DB_Sqlite(@Nullable Context context) 
        super(context, BDname, null, 1);
    

    @Override
    public void onCreate(SQLiteDatabase db) 
        db.execSQL("create table mytable (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)");

    

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) 
        db.execSQL("DROP TABLE IF EXISTS mytable");
        onCreate(db);

    
    public boolean insertData(String name)
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("name", name);
        long result = db.insert("mytable",null, contentValues);
        if (result == -1)
            return false;
        else
            return true;
    
    public ArrayList getAllrecord()
        ArrayList arrayList = new ArrayList();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res = db.rawQuery("select * from mytable",null);
        res.moveToFirst();
        while (res.isAfterLast()==false)
            String t1 = res.getString(0);
            arrayList.add(t1+" - ");
            res.moveToNext();
        
        return arrayList;
    

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_
    android:layout_
    tools:context=".MainActivity"
    android:background="#f2f2f2"
    android:orientation="vertical">


    <TextView
        android:id="@+id/tv1"
        android:layout_
        android:layout_
        android:textSize="25sp"
        android:textColor="@color/colorAccent"
        android:text="Favorite List:">

    </TextView>

    <ListView
        android:layout_
        android:layout_
        android:id="@+id/list_view1"
        android:layout_below="@+id/tv1"
        android:divider="@color/colorPrimary"
        android:dividerHeight="1dp"
        android:layout_weight="1">
    </ListView>




    <TextView
        android:id="@+id/tv"
        android:layout_
        android:layout_
        android:textSize="25sp"
        android:textColor="@color/colorAccent"
        android:layout_weight="0"
        android:text="Game List:"
        android:layout_below="@+id/list_view1">

    </TextView>

    <ListView
        android:id="@+id/list_view"
        android:layout_
        android:layout_
        android:layout_below="@+id/tv"
        android:layout_weight="2"
        android:divider="@color/colorPrimary"
        android:dividerHeight="1dp"
        android:layout_alignParentBottom="true"
        >

    </ListView>



</LinearLayout>

这是我到目前为止所做的,请帮助我提前谢谢你。

【问题讨论】:

如果您想将项目从一个列表发送到另一个列表,只需将其从arrayList 中删除并添加到arrayList1 并在适配器上调用notifyDatasetChanged() 【参考方案1】:

以下应该做你想做的(假设通过发送到意味着移动到):-

public class MainActivity extends AppCompatActivity 

    private static final String TAG = "MainActivity";
    DB_Sqlite db = new DB_Sqlite(this);
    ListView listView1;
    ListView listView;
    ArrayAdapter<String> adapter, adapter1; /* changed to use ArrayAdapter */
    ArrayList<String> arrayList,arrayList1; /* moved (not necessary) */



    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.list_view);
        listView1 = (ListView) findViewById(R.id.list_view1);

        arrayList = new ArrayList<String>();
        arrayList.add("Complex Complex");
        arrayList.add("Trix Complex");
        arrayList.add("Kingdoms");
        arrayList1 = new ArrayList<String>();
        adapter = new ArrayAdapter<>(MainActivity.this,android.R.layout.simple_list_item_1,arrayList);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() 
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) 
                if (position == 0)
                    Intent intent = new Intent(MainActivity.this,cc.class);
                    startActivity(intent);
                
                if (position == 1)
                    Intent intent = new Intent(MainActivity.this,tc.class);
                    startActivity(intent);
                
                if (position == 2)
                    Intent intent = new Intent(MainActivity.this,k.class);
                    startActivity(intent);
                


            
        );
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() 
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long l) 
                if (position == 0) 

                    Boolean result = db.insertData((String) arrayList.get(position));
                    if (result == true)
                        Toast.makeText(MainActivity.this,"Added To Favorite",Toast.LENGTH_SHORT).show();
                    else
                        Toast.makeText(MainActivity.this, "Already Exist", Toast.LENGTH_SHORT).show();
                    

                
                if (position == 1)
                    Toast.makeText(MainActivity.this, "TC Added to Favorites", Toast.LENGTH_SHORT).show();
                
                if (position == 2)
                    Toast.makeText(MainActivity.this, "K Added to Favorites", Toast.LENGTH_SHORT).show();
                
                /*<<<<< the core code that was added >>>>>*/
                arrayList1.add(arrayList.get(position));
                arrayList.remove(position);
                adapter1.notifyDataSetChanged();
                adapter.notifyDataSetChanged();
                return true;
            

        );

        /* added */
        adapter1 = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,arrayList1);
        listView1.setAdapter(adapter1);

    
    public void showData()
        ArrayList arrayList1 = db.getAllrecord();
        final ListAdapter adapter1 = new ArrayAdapter<>(MainActivity.this,android.R.layout.simple_list_item_1,arrayList1);
        listView1.setAdapter(adapter1);
    

结果

第一个 ListView 具有蓝色背景,另一个 ListView 具有绿色背景,以便将一个与另一个区分开来。

刚开始时:-

长按 Trix 复合体后:-

附加

重新评论:-

@AhmedZaqout 大致你需要做的是 a) 添加一列作为 哪个列表的指示符,例如favourite_flag INTEGER DEFAULT 0 b) 用初始值(Kingdons 等)填充 DB,而不是定义 ArrayList 中的值。当活动开始时提取值 根据指标列进入2个列表。如果项目在第一个 是长按更新行以设置指标然后刷新 列表。

然后考虑以下内容:-

DB_SQlite.java

public class DB_Sqlite extends SQLiteOpenHelper 
    public static final String BDname = "data.db";
    public static final int DBVERSION = 1; /*<<<<< ADDED BUT NOT NEEDED */
    public static final String TABLE_FAVOURITES = "mytable";

    public static final String FAVOURITES_COL_ID = BaseColumns._ID; /*<<<< use the Android stock ID name*/
    public static final String FAVOURITES_COL_NAME = "name";
    public static final String FAVOURITES_COL_FAVOURITEFLAG = "favourite_flag"; /*<<<<< NEW COLUMN */

    public DB_Sqlite(@Nullable Context context) 
        super(context, BDname, null, DBVERSION /*<<<<< used constant above */);
    

    @Override
    public void onCreate(SQLiteDatabase db) 
        db.execSQL("create table " + TABLE_FAVOURITES + " (" +
                FAVOURITES_COL_ID + " INTEGER PRIMARY KEY," + /*<<<<< AUTOINCREMENT NOT NEEDED AND IS INEFFICIENT */
                FAVOURITES_COL_NAME + " TEXT, " +
                FAVOURITES_COL_FAVOURITEFLAG + " INTEGER DEFAULT 0" + /*<<<<< COLUMN ADDED */
                ")");
        /*<<<<< Add initial data */
        /* Note indicator will set to non_favourite i.e. 0 */
        ContentValues cv = new ContentValues();
        cv.put(FAVOURITES_COL_NAME,"Complex Complex");
        db.insert(TABLE_FAVOURITES,null,cv);
        cv.clear();
        cv.put(FAVOURITES_COL_NAME,"Trix Complex");
        db.insert(TABLE_FAVOURITES,null,cv);
        cv.clear();
        cv.put(FAVOURITES_COL_NAME,"Kingdoms");
        db.insert(TABLE_FAVOURITES,null,cv);
    

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) 
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVOURITES);
        onCreate(db);

    
    public boolean insertData(String name)
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(FAVOURITES_COL_NAME, name);
        long result = db.insert(TABLE_FAVOURITES,null, contentValues);
        if (result == -1)
            return false;
        else
            return true;
    

    /*<<<<< ADDEDD */
    public Cursor getFavouriteRows(boolean favourites /* true to return favourites (listView 2), false to return non-favourites (ListView 1) */) 
        SQLiteDatabase db = this.getWritableDatabase();
        String whereclause = FAVOURITES_COL_FAVOURITEFLAG + "=?";
        String compare = "<1";
        if (favourites) 
            compare =">0";
        

        return db.query(
                TABLE_FAVOURITES,null,
                FAVOURITES_COL_FAVOURITEFLAG + compare,
                null,null,null,null
        );
    

    /*<<<<< ADDEDD */
    private int setFavourite(long id, boolean favourite_flag) 
        SQLiteDatabase db = this.getWritableDatabase();
        String whereclause = FAVOURITES_COL_ID + "=?";
        String[] whereargs = new String[]String.valueOf(id);
        ContentValues cv = new ContentValues();
        cv.put(FAVOURITES_COL_FAVOURITEFLAG,favourite_flag);
        return db.update(TABLE_FAVOURITES,cv,whereclause,whereargs);
    

    /*<<<<< ADDEDD */
    public int setAsFavourite(long id) 
        return setFavourite(id,true);
    

    /*<<<<< ADDEDD */
    public int setAsNotFavourite(long id) 
        return setFavourite(id, false);
    

    /* Will be unused */
    public ArrayList getAllrecord()
        ArrayList arrayList = new ArrayList();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res = db.rawQuery("select * from mytable",null);
        res.moveToFirst();
        while (res.isAfterLast()==false)
            String t1 = res.getString(0);
            arrayList.add(t1+" - ");
            res.moveToNext();
        
        return arrayList;
    

MainActivity.java

public class MainActivity extends AppCompatActivity 

    private static final String TAG = "MainActivity";
    DB_Sqlite db = new DB_Sqlite(this);
    ListView listView1, listView;
    //ArrayAdapter<String> adapter, adapter1; /*<<<<< commented out as unused */
    //ArrayList<String> arrayList,arrayList1; /*<<<<< commented out as unused */
    Cursor non_favourites_cursor, favourites_cursor; //<<<<< Added as goind to use Cursor Adapter */
    SimpleCursorAdapter non_favourites_adapter, favourites_adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.list_view);
        listView1 = (ListView) findViewById(R.id.list_view1);
        manageBothListViews();

        //arrayList = new ArrayList<String>();
        //arrayList.add("Complex Complex");
        //arrayList.add("Trix Complex");
        //arrayList.add("Kingdoms");
        //arrayList1 = new ArrayList<String>();
        //adapter = new ArrayAdapter<>(MainActivity.this,android.R.layout.simple_list_item_1,arrayList);
        //listView.setAdapter(adapter);

        /*
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() 
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) 
                if (position == 0)
                    Intent intent = new Intent(MainActivity.this,cc.class);
                    startActivity(intent);
                
                if (position == 1)
                    Intent intent = new Intent(MainActivity.this,tc.class);
                    startActivity(intent);
                
                if (position == 2)
                    Intent intent = new Intent(MainActivity.this,k.class);
                    startActivity(intent);
                


            
        );
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() 
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long l) 
                if (position == 0) 

                    Boolean result = db.insertData((String) arrayList.get(position));
                    if (result == true)
                        Toast.makeText(MainActivity.this,"Added To Favorite",Toast.LENGTH_SHORT).show();
                    else
                        Toast.makeText(MainActivity.this, "Already Exist", Toast.LENGTH_SHORT).show();
                    

                
                if (position == 1)
                    Toast.makeText(MainActivity.this, "TC Added to Favorites", Toast.LENGTH_SHORT).show();
                
                if (position == 2)
                    Toast.makeText(MainActivity.this, "K Added to Favorites", Toast.LENGTH_SHORT).show();
                
                arrayList1.add(arrayList.get(position));
                arrayList.remove(position);
                adapter1.notifyDataSetChanged();
                adapter.notifyDataSetChanged();
                return true;
            

        );

        adapter1 = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,arrayList1);
        listView1.setAdapter(adapter1);
        */

    

    @Override
    protected void onDestroy() 
        super.onDestroy();
        non_favourites_cursor.close();
        favourites_cursor.close();
    

    @Override
    protected void onResume() 
        super.onResume();
        manageBothListViews();
    

    public void showData()
        ArrayList arrayList1 = db.getAllrecord();
        final ListAdapter adapter1 = new ArrayAdapter<>(MainActivity.this,android.R.layout.simple_list_item_1,arrayList1);
        listView1.setAdapter(adapter1);
    

    private void manageBothListViews() 
        manageNonFavouritesListView();
        manageFavouritesListView();
    

    private void manageNonFavouritesListView() 
        non_favourites_cursor = db.getFavouriteRows(false);
        if (non_favourites_adapter == null) 
            non_favourites_adapter = new SimpleCursorAdapter(
                    this,
                    android.R.layout.simple_list_item_1,
                    non_favourites_cursor,
                    new String[]DB_Sqlite.FAVOURITES_COL_NAME,
                    new int[]android.R.id.text1,
                    0
            );
            listView.setAdapter(non_favourites_adapter);
            setListViewHandler(listView,false);
         else 
            non_favourites_adapter.swapCursor(non_favourites_cursor);
        
    
    private void manageFavouritesListView() 
        favourites_cursor = db.getFavouriteRows(true);
        if (favourites_adapter == null) 
            favourites_adapter = new SimpleCursorAdapter(
                    this,
                    android.R.layout.simple_list_item_1,
                    favourites_cursor,
                    new String[]DB_Sqlite.FAVOURITES_COL_NAME,
                    new int[]android.R.id.text1,
                    0
            );
            listView1.setAdapter(favourites_adapter);
            setListViewHandler(listView1,true);
         else 
            favourites_adapter.swapCursor(favourites_cursor);
        
    

    private void setListViewHandler(ListView lv,  boolean favourite_flag) 
        if (!favourite_flag) 
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() 
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
                    if (non_favourites_cursor.getString(non_favourites_cursor.getColumnIndex(DB_Sqlite.FAVOURITES_COL_NAME)).equals("Complex Complex")) 
                        Intent intent = new Intent(MainActivity.this,cc.class);
                        startActivity(intent);
                    
                    if (non_favourites_cursor.getString(non_favourites_cursor.getColumnIndex(DB_Sqlite.FAVOURITES_COL_NAME)).equals("Trix Complex")) 
                        Intent intent = new Intent(MainActivity.this,tc.class);
                        startActivity(intent);
                    
                    if (non_favourites_cursor.getString(non_favourites_cursor.getColumnIndex(DB_Sqlite.FAVOURITES_COL_NAME)).equals("Kingdoms"))
                        Intent intent = new Intent(MainActivity.this,k.class);
                        startActivity(intent);
                    
                
            );
            lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() 
                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) 
                    db.setAsFavourite(id);
                    manageBothListViews();
                    return true;
                
            );
         else 
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() 
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
                    if (favourites_cursor.getString(favourites_cursor.getColumnIndex(DB_Sqlite.FAVOURITES_COL_NAME)).equals("Complex Complex")) 
                        Intent intent = new Intent(MainActivity.this,cc.class);
                        startActivity(intent);
                    
                    if (favourites_cursor.getString(favourites_cursor.getColumnIndex(DB_Sqlite.FAVOURITES_COL_NAME)).equals("Trix Complex")) 
                        Intent intent = new Intent(MainActivity.this,tc.class);
                        startActivity(intent);
                    
                    if (favourites_cursor.getString(favourites_cursor.getColumnIndex(DB_Sqlite.FAVOURITES_COL_NAME)).equals("Kingdoms"))
                        Intent intent = new Intent(MainActivity.this,k.class);
                        startActivity(intent);
                    
                
            );
        
    

查看 cmets 这使用 CursorAdapter 而不是 ArrayAdapter。 这使用创建数据库时存储在数据库中的值(名称 Kingdoms 等)。因此,您应该在运行更改后的代码之前卸载应用程序或删除应用程序的数据。

【讨论】:

非常感谢你,这很有帮助,但我现在有两个问题 1) 我希望在关闭应用程序后留在第二个列表视图中。 2)我希望它像在第一个列表视图中一样做同样的事情(打开分配的活动)。但非常感谢你。 @AhmedZaqout 大致你需要做的是a)添加一个列作为哪个列表的指示符,例如favourite_flag INTEGER DEFAULT 0 b) 用初始值(Kingdons 等)填充 DB,而不是在 ArrayList 中定义值。当活动开始时,根据指标列将值提取到 2 个列表中。如果第一个项目是长按,则更新行以设置指示器,然后刷新列表。 非常感谢,这对您很有帮助,您是最棒的。 在此之前,您如何感谢您的帮助,但有一些事情我希望您帮助我,有什么方法可以在我更改手机上的区域设置时所有数据都更改为该区域设置我尝试了很多方法,但没有一个起作用我得到的只是数字(可能是字符串的值)我不确定。 @MikeT @AhmedZaqout 答案here 似乎是一个很好的答案。

以上是关于将一行从一个列表视图发送到另一个列表视图的主要内容,如果未能解决你的问题,请参考以下文章

如何将列表视图中的数据从一个片段发送到另一个片段

将活动之间的数据从列表视图传递到另一个活动

当我单击列表视图的操作项时,将文本从列表视图传递到另一个活动

是否可以将一个对象从一个片段发送到另一个片段?

从列表视图中删除一行后刷新片段

如何将数据从一个 Fragment 发送到另一个 Fragment?