gpt4 book ai didi

android - 从列表中设置ContentView (Kotlin)

转载 作者:行者123 更新时间:2023-12-02 15:57:00 24 4
gpt4 key购买 nike

您好,我有一个食物列表,其中还包含我想要在单击时膨胀的布局。

class MainActivity : AppCompatActivity() {

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

val food = listOf(
Foods("Creme Brulee", "A rich egg dessert with torched sugar on top.", "French", R.drawable.cremebrulee1, R.layout.food_cremebrulee),
Foods("Hamburger", "Something something", "Spanish", R.drawable.person2, R.layout.food_hamburger),
Foods("Grilled Cheese", "Something something", "Chinese", R.drawable.person3, R.layout.food_hamburger),
Foods("French Onion Soup", "Something something", "French", R.drawable.person4, R.layout.food_hamburger),
Foods("Salmon", "Something something", "German", R.drawable.person2, R.layout.food_hamburger),
Foods("Fish Tacos", "Something something", "Dutch", R.drawable.person3, R.layout.food_hamburger),
Foods("Vegetable Sushi", "Something something", "Asian", R.drawable.person4, R.layout.food_hamburger),
Foods("Fried Egg", "Something something", "Thai", R.drawable.person1, R.layout.food_hamburger),
Foods("Vinagrette", "Thai style vinagrette with peanut butter", "Indian", R.drawable.person2, R.layout.food_hamburger)
)


myCustomFood.apply {
layoutManager = LinearLayoutManager(this@MainActivity)
adapter = FoodAdapter(food) {
d("marlon", "hi from MainActivity!")
//startActivity(Intent(this@MainActivity, FoodDetailView::class.java))
startActivity(Intent(this@MainActivity, FoodDetailView::class.java))
}
}
}
}
class FoodDetailView : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView() <--- What do I put here in order to grab the appropriate R.layout when a food on the list is clicked?
}
}

正如您所看到的,第一个选择是 R.layout.cremebrulee1,其他选择是 R.layout.hamburger,我应该在 setContentView 中放入什么才能从列表中获取 R.layout?

最佳答案

您可以将布局 ID 放入 extras 中:

val intent = Intent(this@MainActivity, FoodDetailView::class.java)
intent.putExtra("EXTRA_LAYOUT", food.layout)
startActivity(intent)

然后将其返回到您的目标 Activity 中:

val layoutId = intent.getIntExtra("EXTRA_LAYOUT", 0)
if (layoutId > 0) {
setContentView(layoutId)
}

关于android - 从列表中设置ContentView (Kotlin),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59062217/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com