当前位置: 首页 > 知识库问答 >
问题:

在 Kotlin 中的两个活动之间传递对象实例

傅正阳
2023-03-14

我想知道是否有人可以帮助我用Intent修复此错误?

我有两个活动要连接:网格视图“MainActivity.kt”的第一个活动,列表视图“Main2Activity.kt”的第二个活动,我有来自“Main2Activity.kt”的2个对象实例(adapter1,adapter2 ),当单击“MainActivity.kt”中的特定图像时,我想传递特定的对象实例(adapter1)或(adapter2)

注意:我使用的是 BaseAdapter

这是一个主要活动.kt

class MainActivity : AppCompatActivity() {

var adapter:FoodAdapter?=null
var listOfFoods =ArrayList<Food>()
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(layout.activity_main)


    // load foods
    listOfFoods.add(Food("Coffee","   Coffee preparation is", a))
    listOfFoods.add(Food("Coffee","   Coffee preparation is", b))
    listOfFoods.add(Food("Coffee","   Coffee preparation is", c))
    listOfFoods.add(Food("Coffee","   Coffee preparation is", d))

    adapter= FoodAdapter(this,listOfFoods)

    gvListFood.adapter =adapter

}


class  FoodAdapter: BaseAdapter {
    var listOfFood= ArrayList<Food>()
    var context: Context?=null
    constructor(context:Context,listOfFood:ArrayList<Food>):super(){
        this.context=context
        this.listOfFood=listOfFood
    }
    override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View? {
        val food = this.listOfFood[p0]
        var inflator = context!!.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        var foodView= inflator.inflate(layout.food_ticket,null)
        foodView.ivFoodImage.setImageResource(food.image!!)
        foodView.ivFoodImage.setOnClickListener {


            if (foodView.ivFoodImage.context!!.equals(a) ) {
                val intent = Intent(context, Main2Activity::class.java)
                intent.putExtra(Main2Activity.EXTRA_ADAPTER_MODE, AdapterType.ADAPTER_TYPE_2.ordinal)
                    intent.putExtra("name", food.name!!)
                    intent.putExtra("des", food.des!!)
                    intent.putExtra("image", food.image!!)

                    context!!.startActivity(intent)

            }
            else if (foodView.ivFoodImage.context!!.equals(b)) {
                val intent = Intent(context, Main2Activity::class.java)
                intent.putExtra(Main2Activity.EXTRA_ADAPTER_MODE, AdapterType.ADAPTER_TYPE_2.ordinal)
                    intent.putExtra("name", food.name!!)
                    intent.putExtra("des", food.des!!)
                    intent.putExtra("image", food.image!!)
                    context!!.startActivity(intent)

           }
        }
        return foodView
    }

    override fun getItem(p0: Int): Any {
        return listOfFood[p0]
    }

    override fun getItemId(p0: Int): Long {
        return p0.toLong()
    }

    override fun getCount(): Int {

        return listOfFood.size
    }

}
}

这里有Main2Activity.kt

class Main2Activity : AppCompatActivity() {
companion object {
    val EXTRA_ADAPTER_MODE = "extra_adapter_mode"
}
var adapter1: FoodAdapter? = null
var adapter2: FoodAdapter2? = null
var listOfFoods2 = ArrayList<Food>()
var listOfFoods3 = ArrayList<Food>()
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main2)


    val bundle = intent?.getIntExtra(EXTRA_ADAPTER_MODE, AdapterType.ADAPTER_TYPE_1.ordinal)
    val name = bundle?.let { AdapterType.fromOrdinal(it) }
    val des = bundle?.let { AdapterType.fromOrdinal(it) }
    val image = bundle?.let { AdapterType.fromOrdinal(it) }

    //val bundle = intent.extras
    //val name = bundle.getString("name")
    //val des = bundle.getString("des")
    //val image = bundle.getInt("image")



    /*
    ivFoodImage2?.let {
        it.setImageResource(image)
    }

    tvName2?.let {
        it.text = name
    }

    tvDes2?.let {
        it.text = des
    }
    */





    // load foods2
    listOfFoods2.add(Food("Coffee", "   Coffee1 preparation is", R.drawable.a))
     listOfFoods2.add(Food("Coffee", "   Coffee2 preparation is", R.drawable.b))

         //listOfFoods2.add(Food("Coffee","   Coffee preparation is",R.drawable.c))
         //listOfFoods2.add(Food("Coffee","   Coffee preparation is",R.drawable.d))


    // load foods3


    //listOfFoods3.add(Food("Coffee","   Coffee preparation is",R.drawable.a))
    //listOfFoods3.add(Food("Coffee","   Coffee preparation is",R.drawable.b))
    listOfFoods3.add(Food("Coffee", "   Coffee3 preparation is", R.drawable.c))
    listOfFoods3.add(Food("Coffee", "   Coffee4 preparation is", R.drawable.d))



   if(adapter1 ==lvFoods2.adapter) {
       adapter1 = FoodAdapter(listOfFoods2, this)
       lvFoods2.adapter = adapter1
    } else if (adapter2==lvFoods2.adapter) {
       adapter2 = FoodAdapter2(listOfFoods3, this)
       lvFoods2.adapter = adapter2
     }

    }


class FoodAdapter : BaseAdapter {
    var context: Context? = null
    var listOfFoodsLocal2 = ArrayList<Food>()

  constructor(listOfFoods2: ArrayList<Food>, context: Context) : super() {
        this.listOfFoodsLocal2 = listOfFoods2
        this.context = context
    }

    override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View {
        val food = this.listOfFoodsLocal2[p0]
        var inflator = context!!.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        val foodView = inflator.inflate(R.layout.food_ticket2, null)


                 foodView.ivFoodImage2?.let {
                     it.setImageResource(food.image!!)
                 }
        foodView.tvName2?.let {

            it.text = food.name!!
        }
        foodView.tvDes2?.let {
            it.text = food.des!!
        }

        foodView.ivFoodImage2.setOnClickListener {

            //move to next
            val intent = Intent(context, FoodDetails::class.java)
            intent.putExtra("name", food.name!!)
            intent.putExtra("des", food.des!!)
            intent.putExtra("image", food.image!!)

            context!!.startActivity(intent)

        }
        return foodView

    }


    override fun getItem(p0: Int): Any {
        return listOfFoodsLocal2[p0]
    }

    override fun getItemId(p0: Int): Long {
        return p0.toLong()
    }

    override fun getCount(): Int {
        return listOfFoodsLocal2.size
    }

}

class FoodAdapter2 : BaseAdapter {
    var context: Context? = null
    var listOfFoodsLocal3 = ArrayList<Food>()

  constructor(listOfFoods3: ArrayList<Food>, context: Context) : super() {
        this.listOfFoodsLocal3 = listOfFoods3
        this.context = context
    }

    override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View {
        val food = this.listOfFoodsLocal3[p0]
        var inflator = context!!.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        val foodView = inflator.inflate(R.layout.food_ticket2, null)


         foodView.ivFoodImage2?.let {
             it.setImageResource(food.image!!)
         }
        foodView.tvName2?.let {
            it.text = food.name!!
        }
         foodView.tvDes2?.let {
             it.text = food.des!!
         }



        foodView.ivFoodImage2.setOnClickListener {

            //move to next
            val intent = Intent(context, FoodDetails::class.java)
            intent.putExtra("name", food.name!!)
            intent.putExtra("des", food.des!!)
            intent.putExtra("image", food.image!!)

            context!!.startActivity(intent)

        }
        return foodView

    }


    override fun getItem(p0: Int): Any {
        return listOfFoodsLocal3[p0]
    }

    override fun getItemId(p0: Int): Long {
        return p0.toLong()
    }

    override fun getCount(): Int {
        return listOfFoodsLocal3.size
    }

}
}

下面是枚举类

enum class AdapterType {
ADAPTER_TYPE_1,
ADAPTER_TYPE_2,
ADAPTER_TYPE_3;


companion object {
     fun fromOrdinal(name:String,des:String,image: Int): AdapterType? {
        return AdapterType.values().firstOrNull { it.ordinal == image}



     }
}
}

共有2个答案

范成周
2023-03-14

不能在活动之间传递适配器。至少以一种干净的方式,谷歌推荐。适配器既不实现可打包接口,也不实现可序列化接口。因此,正如 Nino Handler 所指出的,一般规则 - 使用 Intent 发送数据(而不是适配器本身),这些数据应该用于创建适配器。

公冶同
2023-03-14

创建一个 IntDef,如下所示:

@Retention(SOURCE)
@IntDef({ADAPTER_MODE_1, ADAPTER_MODE_2, ADAPTER_MODE_3})
public @interface AdapterMode {}
public static final int ADAPTER_MODE_1 = 0;
public static final int ADAPTER_MODE_2 = 1;
public static final int ADAPTER_MODE_3 = 2;
//...

并将int添加到包中。对于静态编程语言,您必须使用配套对象来定义变量,例如

class FirstActivity {
    companion object { 
         val ADAPTER_MODE1 = 0
         val ADAPTER_MODE2 = 1
         val ADAPTER_MODE3 = 2
         //...
    }
}

因此,您可以将无限的适配器案例传递给第二个活动

编辑:Kotlin不支持@IntDef,所以你应该使用一个enum:

enum class AdapterType {
    ADAPTER_TYPE_1,
    ADAPTER_TYPE_2,
    ADAPTER_TYPE_3;

    companion object {
        fun fromOrdinal(ordinal: Int): AdapterType? {
            return AdapterType.values().firstOrNull { it.ordinal == ordinal }
        }
    }
}

然后像这样使用它:

class FirstActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val intent = Intent(this, SecondActivity::class.java)
        intent.putExtra(SecondActivity.EXTRA_ADAPTER_MODE, AdapterType.ADAPTER_TYPE_2.ordinal)
    }
}

取回它就像:

class SecondActivity : AppCompatActivity() {
    companion object {
        val EXTRA_ADAPTER_MODE = "extra_adapter_mode"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //...
        val adapterTypeOrdinal = intent?.getIntExtra(EXTRA_ADAPTER_MODE, AdapterType.ADAPTER_TYPE_1.ordinal)
        val adapterType = adapterTypeOrdinal?.let { AdapterType.fromOrdinal(it) }

        // do something with it
    }
}
 类似资料:
  • 我正在开发一个由多个活动组成的Android应用程序,我必须在它们之间传递ab对象,但我不能通过使用意图传递它,因为对象的类没有实现可序列化,我怎么做?我无法修改我的类的源代码。谢谢:)

  • 我试图将一个活动(LensActivity)中的ArrayList中的值传递给我的主活动上的TextView。在这个网站上,我找到了Intent方法并进行了实验,但似乎无法传递它,信息被提取到字符串lensString中,并传递到Intent,但在主活动中似乎没有传递或获取TextView,在一些实验中,由于getIntent在主活动中,我得到了一个空指针。 这是LensActivity的代码,它

  • 我试图在我的android应用程序中的两个活动之间传递数据,我想使用HashMap(我不想使用Intent)。以下是我的代码: DataHolder.java 在第一个活动中设置值 在其他活动中获得价值 当我用它在activity1到activity2之间传递数据时,它会起作用,但在那之后,当在activity2到activity3之间传递数据时,返回null,因此强制转换为(整数)会导致错误。在

  • 背景: 有两项活动 1x(主活动),1x(子活动-具有列表视图的活动) 主活动扩展了碎片活动,信息将在碎片中使用 单击主活动的菜单项时,子活动将打开 为ListView使用HashMap 我的目标: 单击项的HashMap值应发送回主活动,子活动(带有ListView)应关闭 问题: 我认为我犯了一个巨大的错误,但我无法解决它。 从onOptionsItemSelected和onActivityR

  • 我有两项活动。两者都已实现surfaceview。在第一个活动中,我有一个名为score1的变量,我想将score1中的值传递给第二个活动。 每次我运行应用程序时,它在完成第一个活动后崩溃,并尝试加载第二个活动。在我编写代码以获取第二个活动中的额外意图之前,一切都很好。 我的第一个活动有这样的意图: 在我的第二个活动中,以下代码试图获取score1变量的值: 我不明白为什么每次activity o

  • 假设你有两个活动-A和B,你从A开始B。在B中,你有一个任务。如果任务完成,您希望返回到按下when back键,如果没有,您希望取消整个应用程序。但在解除后,你可以从最近的应用程序菜单中恢复B。如果在那之后你需要同样的后退键的行为。 因此,我想放弃一个活动或整个应用程序(但简历的可能性)。有什么办法可以做到这一点吗?