在listView中未选择任何项目时吐司

问题描述 投票:0回答:1

嗨,伙计们我正在尝试做这项工作:

         button.setOnClickListener {
            if (list1.choiceMode == android.widget.ListView.CHOICE_MODE_NONE){
                toast("You need to choose an item first")
            }
            else {
                val builder = AlertDialog.Builder(this)
                builder.setTitle("Alert")
                builder.setMessage("This service requires data?")
                builder.setPositiveButton("Yes", { dialogInterface: DialogInterface, i: Int ->
                    ListView.visibility = View.GONE
                    website.visibility = View.VISIBLE
                })
                builder.setNegativeButton("No", { dialogInterface: DialogInterface, i: Int -> })
                builder.show()
            }

        }

我试图在用户按下按钮但是他没有从列表1中选择任何项目时显示消息。如果一切正常,我希望它将listView可见性设置为已消失且网站可见性设置为可见。

按下按钮时我得到的只是吐司信息。

编辑:

    val nameofanimals = arrayOf("cat","dog","parrot")

internal lateinit var adapteranimals: ArrayAdapter<String>

这是我的清单:

val list1 = findViewById(R.id.list1) as ListView


    <ListView
        android:id="@+id/list1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:choiceMode="singleChoice"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:listSelector="@android:color/darker_gray"
        android:textSize="10dp"
        android:visibility="gone">


    </ListView>

我的适配器:

adapteranimals = ArrayAdapter(
        this@MainActivity,
        R.layout.list1layout,
        nameofanimals)
list1.adapter = adapteranimals

现在我需要在没有选择cat,dog或parrot的情况下显示toast消息,并且想要将webviewer和listview布局的可见性设置为可见,并在用户实际选择列表中的某个选项时消失

android listview if-statement kotlin
1个回答
0
投票

为了使您的项目可以在列表中选择,您需要在列表视图上调用两个关键方法。

button.setOnClickListener添加这两行之前

        list1.setItemsCanFocus(false);
        list1.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

然后在你的onClickListener里面做这个:

Object selectedObj = list1.getSelectedItem(); 

if (selectedObj == null) {
 showToast();
} else {
 doSomethingElse();
}
© www.soinside.com 2019 - 2024. All rights reserved.