我是靠谱客的博主 欢喜春天,最近开发中收集的这篇文章主要介绍android listview 选中状态,Android:在ListView打开时将项目设置为选中状态?,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

我正在使用适配器并且不想设置自定义背景颜色,但在drawable xml中使用android:state_selected。 SetSelection对我不起作用,但也许这也是因为我需要SetNotifyDataChanged,这表明Selected State不是持久的。

我还发现ListView中项目的Selected状态不是持久的,因为SetNotifyDataChanged导致更新ListView布局,清除它们。 在适配器的GetView中将项目设置为Selected也太快了。

最后,在更改listview的布局之后,我为所选项的视图设置了Selected状态,这是在触发LayoutChange事件时(在Java中,它可能附加到ListView的OnLayoutChangeListener)。

为了使它变得非常简单,我将所选项目的视图存储为Adapter的SelectedItemView。 在ListView的LayoutChange事件处理程序中,我只是将适配器的SelectedItemView.Selected设置为true。

这是我的Activity中的代码,我为ListView设置了适配器,也订阅了LayoutChange(或者在Java中附加了一个OnLayoutChangeListener)

ringTonesListView.Adapter = ringTonesListAdapter; ringTonesListView.LayoutChange += (s, layoutChangeArgs) => { //At this stage the layout has been updated and the Selected can be set to true for the view of the selected item. This will result in android:state_selected logic to be applied as desired and styling can be completely done per layout in Resources. ringTonesListAdapter.SelectedItemView.Selected = true; };

这是我的适配器代码:

public class RingTonesListAdapter : BaseAdapter{ ListItems { get; set; } public override View GetView(int position, View convertView, ViewGroup parent) { View view = convertView; // re-use an existing view, if one is available // otherwise create a new one if (view == null) { view = Context.LayoutInflater.Inflate(Resource.Layout.AlertSoundItem, parent, false); view.Click += SelectRingTone; } RingTone ringTone = this[position]; if (ringTone.Selected) { //==> Important //Store this view since it's the view for the Selected Item SelectedItemView = view; //Setting view.Selected to true here doesn't help either, since Selected will be cleared after. } return view; } private void SelectRingTone(object sender, EventArgs args) { View view = (View)sender; string title = view.FindViewById(Resource.Id.ringToneTitle).Text; RingToneItem ringToneItem = Items.First(rt => rt.Title == title); if (!ringToneItem.Selected) { //The RingTone was not selected and is selected now //Deselect Old and Select new foreach (RingToneItem oldItem in Items.Where(rt => rt.Selected)) { oldItem.Selected = false; } // Select New RingTone ringToneItem.Selected = true; //Update the ListView. //This will result in removal of Selected state for all Items when the ListView updates it's layout NotifyDataSetChanged(); } //Now play the test sound NotifierService.TestSound(Context, ringToneItem); } public View SelectedItemView { get; set; } }

最后

以上就是欢喜春天为你收集整理的android listview 选中状态,Android:在ListView打开时将项目设置为选中状态?的全部内容,希望文章能够帮你解决android listview 选中状态,Android:在ListView打开时将项目设置为选中状态?所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(36)

评论列表共有 0 条评论

立即
投稿
返回
顶部