在新活动上使用ListView显示列表。列表取决于单击按钮

发布于 2025-01-24 13:26:24 字数 5811 浏览 4 评论 0原文

我的主进性有两个按钮。这两个按钮都打开相同的新活动,但根据单击哪个按钮显示不同的listView。我一直在玩它,到目前为止,我可以将其显示在主动脉上,但无法弄清楚如何获得它,以便在第二个活动中打开它。我认为我需要以某种方式在新活动中使用适配器,然后以某种方式将ListArray传递给它?我无法使它工作。

我目前的代码是工作是

mainActivity.kt


class MainActivity : AppCompatActivity() {


    lateinit var button: Button
    lateinit var button2: Button
    lateinit var test_list: ListView

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

        button = findViewById(R.id.button)
        button2 = findViewById(R.id.button2)
        button.setOnClickListener {

            val intent = Intent(this@MainActivity, ItemsList::class.java)

            test_list = findViewById(R.id.test_list)
            var breeds = arrayOf("")
            var breeds2 = arrayListOf<Breeds>()
            breeds2.add(Breeds("type1"))
            breeds2.add(Breeds("type2"))
            breeds2.add(Breeds("type3"))
            breeds2.add(Breeds("type4"))
            breeds2.add(Breeds("type5"))
            var adapter: MyAdapter
                adapter = MyAdapter(this, breeds2)

                test_list.adapter = adapter
                test_list.setOnItemClickListener { parent, view, position, id ->
                    Log.d("Test list", breeds[position])
                    startActivity(intent)
            }

        }

        button2.setOnClickListener {

            val intent = Intent(this@MainActivity, ItemsList::class.java)

            test_list = findViewById(R.id.test_list)
            var breeds = arrayListOf("")
            var breeds2 = arrayListOf<Breeds>()
            breeds2.add(Breeds("breed1"))
            breeds2.add(Breeds("breed2"))
            breeds2.add(Breeds("breed3"))
            breeds2.add(Breeds("breed4"))
            breeds2.add(Breeds("breed5"))
            var adapter: MyAdapter
            adapter = MyAdapter(this,breeds2)

            test_list.adapter = adapter
            test_list.setOnItemClickListener { parent, view, position, id ->
                Log.d("Test list", breeds[position])
               startActivity(intent)
            }
        }
    }
}


MyAdapter.kt

import android...

class MyAdapter(private val context: Context, private val dataSource :ArrayList<Breeds>) : BaseAdapter(){

    private val inflater: LayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)as LayoutInflater

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

    override fun getItem(position: Int): Any {
        return dataSource[position]
    }

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

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        var rowView:View = inflater.inflate(R.layout.activity_items_list, parent, false)
        val textView : TextView = rowView.findViewById(R.id.list_item_name)
        textView.text = dataSource.get(position).breed
        return rowView
    }

}


breeds.kt

class Breeds {
    var breed : String =""

    constructor(breed: String) {
        this.breed = breed
    }
}

//I want to have the list view open up in this activity

ItemsList.kt

import...

class ItemsList : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_items_list)

    }
}

//my xml files are

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@id/button"

       />

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        android:id="@+id/test_list"/>

</androidx.constraintlayout.widget.ConstraintLayout>

activity_items_list.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/list_item_name"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_margin="10dp"
        android:textColor="@color/black"
        />

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        android:id="@+id/test_list"/>

</androidx.constraintlayout.widget.ConstraintLayout>


I have two buttons on my MainActivity. Both buttons open the same new activity but show a different listView depending on which one is clicked. I have been playing about with it and up to now I can get it to show on the MainActivity but can not figure out how get it so that it opens up on the second activity instead. I figure I need to somehow use the adapter in the new activity and then somehow pass the ListArray to it?? I have not been able to get it to work.

the code I have at the moment is that works is

MainActivity.kt


class MainActivity : AppCompatActivity() {


    lateinit var button: Button
    lateinit var button2: Button
    lateinit var test_list: ListView

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

        button = findViewById(R.id.button)
        button2 = findViewById(R.id.button2)
        button.setOnClickListener {

            val intent = Intent(this@MainActivity, ItemsList::class.java)

            test_list = findViewById(R.id.test_list)
            var breeds = arrayOf("")
            var breeds2 = arrayListOf<Breeds>()
            breeds2.add(Breeds("type1"))
            breeds2.add(Breeds("type2"))
            breeds2.add(Breeds("type3"))
            breeds2.add(Breeds("type4"))
            breeds2.add(Breeds("type5"))
            var adapter: MyAdapter
                adapter = MyAdapter(this, breeds2)

                test_list.adapter = adapter
                test_list.setOnItemClickListener { parent, view, position, id ->
                    Log.d("Test list", breeds[position])
                    startActivity(intent)
            }

        }

        button2.setOnClickListener {

            val intent = Intent(this@MainActivity, ItemsList::class.java)

            test_list = findViewById(R.id.test_list)
            var breeds = arrayListOf("")
            var breeds2 = arrayListOf<Breeds>()
            breeds2.add(Breeds("breed1"))
            breeds2.add(Breeds("breed2"))
            breeds2.add(Breeds("breed3"))
            breeds2.add(Breeds("breed4"))
            breeds2.add(Breeds("breed5"))
            var adapter: MyAdapter
            adapter = MyAdapter(this,breeds2)

            test_list.adapter = adapter
            test_list.setOnItemClickListener { parent, view, position, id ->
                Log.d("Test list", breeds[position])
               startActivity(intent)
            }
        }
    }
}


MyAdapter.kt

import android...

class MyAdapter(private val context: Context, private val dataSource :ArrayList<Breeds>) : BaseAdapter(){

    private val inflater: LayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)as LayoutInflater

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

    override fun getItem(position: Int): Any {
        return dataSource[position]
    }

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

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        var rowView:View = inflater.inflate(R.layout.activity_items_list, parent, false)
        val textView : TextView = rowView.findViewById(R.id.list_item_name)
        textView.text = dataSource.get(position).breed
        return rowView
    }

}


breeds.kt

class Breeds {
    var breed : String =""

    constructor(breed: String) {
        this.breed = breed
    }
}

//I want to have the list view open up in this activity

ItemsList.kt

import...

class ItemsList : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_items_list)

    }
}

//my xml files are

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@id/button"

       />

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        android:id="@+id/test_list"/>

</androidx.constraintlayout.widget.ConstraintLayout>

activity_items_list.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/list_item_name"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_margin="10dp"
        android:textColor="@color/black"
        />

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        android:id="@+id/test_list"/>

</androidx.constraintlayout.widget.ConstraintLayout>


如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

丑丑阿 2025-01-31 13:26:24

您可以从技术上 找到一种通过 s在意图之间传递列表的方法,但是传递对象开始变得有些复杂,因为那里您可以将一组有限的类型集放入A bundle /a>,以及在这种情况下可以通过多少数据的限制

,因为您只有string s的列表,您可以使用 putextra采用字符串数组的方法,然后将其拉出其他活动:

// in first activity
intent.putExtra("list key", breeds2.toTypedArray())

// in second activity - could be missing (null result) so I'm using an empty default
val list = intent.getStringArrayExtra("list key")?.toList() ?: emptyList()
// now use it in your list adapter

但是通常这不是一个好主意。理想情况下,您的数据(即列表)将存储在两个活动都可以访问它的地方,并且您在活动之间的所有通过都是某种ID,因此Activity 2可以 fetch 正确的列表。对于此示例的一种简单方法是将它们粘贴在两种活动都可以看到的顶级val s中:

// this needs to be outside of both Activities - stick it in another file if you like
val list1 = listOf(Breed("breed1"), Breed("breed2")) // etc
val list2 = listOf(Breed("type1"), Breed("type2")) // etc

// button 1 listener:
intent.putExtra("list type", 1)

// button 2 listener:
intent.putExtra("list type", 2)


// in activity 2:
val listType = intent.getIntExtra("list type") // missing default is -1
val listToUse = if (listType == 1) list1 else list2 // simple either/or fallback
// use the list in your list adapter

但是,如果您的数据可以更改(如修改的列表),则需要为坚持该数据,例如sharedPreferencesdatastore或数据库。您可能会有另一个提供数据的类,您的活动可以在其中请求特定列表。

这不是我如何组织列表或获取它们的方式,而是希望这给您基本的想法 - 将数据存储在应用程序中的其他位置,并让活动通过简单的标识符,以便它们可以获取特定的数据,而是而不是尝试通过活动之间的整个数据结构

You could technically find a way to pass a list between two Activitys through an Intent, but passing objects starts to get a little complicated because there are a limited set of types you can put into a Bundle, and limitations on how much data you can pass

In this case, since you just have a list of Strings, you could use the putExtra method that takes a String array, and pull it out in the other activity:

// in first activity
intent.putExtra("list key", breeds2.toTypedArray())

// in second activity - could be missing (null result) so I'm using an empty default
val list = intent.getStringArrayExtra("list key")?.toList() ?: emptyList()
// now use it in your list adapter

But generally that's not a good idea. Ideally, your data (i.e. the lists) would be stored where both Activities can access it, and all you pass between Activities is some kind of ID, so Activity 2 can fetch the correct list. An easy way for this example is to just stick them in top-level vals that both Activities can see:

// this needs to be outside of both Activities - stick it in another file if you like
val list1 = listOf(Breed("breed1"), Breed("breed2")) // etc
val list2 = listOf(Breed("type1"), Breed("type2")) // etc

// button 1 listener:
intent.putExtra("list type", 1)

// button 2 listener:
intent.putExtra("list type", 2)


// in activity 2:
val listType = intent.getIntExtra("list type") // missing default is -1
val listToUse = if (listType == 1) list1 else list2 // simple either/or fallback
// use the list in your list adapter

but if your data can change (like modified lists), you'll need to be persisting that data, e.g. in SharedPreferences, a DataStore, or a database. You'd probably have another class that provides data, where your activities can request a particular list.

This isn't exactly how I'd organise the lists or fetch them, but hopefully that gives you the basic idea - store the data elsewhere in the app, and let activities pass simple identifiers so they can fetch a particular piece of data, rather than trying to pass entire data structures between activities

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文