我正在尝试在按下按钮时显示一条消息,但列表1中未选择任何内容。如果选择了某个项目,我希望它可以将listView布局的可见性设置为“消失”,并将网站布局的可见性设置为“可见”。
无论如何,按下按钮时我只会得到吐司消息。
代码如下:
我的按钮:
button1.setOnClickListener {
var selectedObj = list1.getSelectedItem()
if (selectedObj == null) {
toast("You need to choose an item form the list first")
}
else {
val builder = AlertDialog.Builder(this)
builder.setTitle("Warning")
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()
}
}
这是我的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"
</ListView>
我的代码:
val nameofanimals = arrayOf("cat","dog","parrot")
val list1 = findViewById(R.id.list1) as ListView
internal lateinit var adapteranimals: ArrayAdapter<String>
我的适配器:
adapteranimals = ArrayAdapter(
this@MainActivity,
R.layout.list1layout,
nameofanimals)
list1.adapter = adapteranimals
Tyvm提前为您提供支持
致谢。
答案 0 :(得分:0)
在设置选择模式时,ListView不存储selectedItem位置。它存储选中项目的位置。
签出
class MainActivity : AppCompatActivity() {
private lateinit var listView:ListView
internal lateinit var adapteranimals: ArrayAdapter<String>
val nameofanimals = arrayOf("cat","dog","parrot")
private lateinit var btn1:Button
private lateinit var myobject:String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
listView = findViewById<ListView>(R.id.list1)
btn1 = findViewById<Button>(R.id.btn1)
adapteranimals = ArrayAdapter(
this@MainActivity,
R.layout.list1layout,
nameofanimals)
listView.adapter = adapteranimals
btn1.setOnClickListener {
val pos = listView.getCheckedItemPosition()
myobject = listView.getAdapter().getItem(pos) as String
Log.d("Selected item",myobject);
}
}
}
答案 1 :(得分:0)
您正在尝试从列表访问变量,并且希望列表存储该变量位置。但是不幸的是列表没有保存点击项的位置。使用此代码,单击的项目就位。
ListView list = (ListView) findViewById(R.id.listview);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Object listItem = list.getItemAtPosition(position);
ListView.visibility = View.GONE
website.visibility = View.VISIBLE
//you can get the list item clicked in position variable
}
});