【发布时间】:2020-02-18 01:00:02
【问题描述】:
我对 android 中的 ListView 有疑问。我添加了一个包含 30 个项目的列表,这意味着我需要向下滚动。我使用如下适配器:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#70292929"
android:layout_gravity="top|right"
android:orientation="horizontal">
<TableLayout
android:id="@+id/tablelayout1"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableRow android:gravity="left">
<ListView
android:id="@+id/listview1"
android:background="#1b4f72"
android:layout_weight="0.5"
android:layout_gravity="top|left"
android:layout_width="10px"
android:layout_height="match_parent">
</ListView>
</TableRow>
</TableLayout>
</LinearLayout>
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
this.RequestWindowFeature(Android.Views.WindowFeatures.NoTitle);
SetContentView(Resource.Layout.Main);
LayoutInflater.Inflate(Resource.Layout.MENU, null);
Android.Views.View globalMENUVIEW = LayoutInflater.Inflate(Resource.Layout.MENU, null); //Listview layout
AlertDialog globalBUILDER = new AlertDialog.Builder(this).Create();
globalBUILDER.Window.SetBackgroundDrawableResource(Resource.Drawable.transparant);
globalBUILDER.Window.SetGravity(Android.Views.GravityFlags.Top | Android.Views.GravityFlags.Right);
globalBUILDER.SetView(globalMENUVIEW);
globalBUILDER.SetCanceledOnTouchOutside(true);
globalBUILDER.Window.SetLayout(800, 500);
globalBUILDER.Show();
globalLISTVIEW1 = globalMENUVIEW.FindViewById<ListView>(Resource.Id.listview1);
List<String> mainMENU = new List<String>();
for (int i = 0; i < 30; i++)
{
mainMENU.Add("hello" + i);
}
globalLISTVIEW1.Adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, mainMENU.ToArray());
//Set item 5 as orange background
for (int i = 0; i < globalLISTVIEW1.ChildCount; i++)
{
if (i == 5) { globalLISTVIEW1.GetChildAt(i).SetBackgroundColor(Android.Graphics.Color.Orange); }
else { globalLISTVIEW1.GetChildAt(i).SetBackgroundColor(Android.Graphics.Color.Transparent); }
}
}
现在我在 itemindex 0 上设置了背景颜色。但是当我向下滚动时,另一个项目也有背景颜色。
我认为 ListView 使用回收导致此行为的项目。
现在我的实际问题。在我的情况下,我永远不会使用超过 30 个项目并且有红色可以通过将以下值添加到适配器来禁用回收。
但我不知道如何实际执行此操作以及我将把这段代码准确地放在哪里?
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemViewType(int position) {
return position;
}
【问题讨论】:
-
ListView不会自动回收其视图,RecyclerView会。如果您使用的是ListView,您可以在此处发布您设置背景的代码吗? -
@Giorgio 我已经用更多代码更新了我的问题,我是如何设置背景的。我将项目索引 5 设置为橙色,其余设置为透明。
-
你也可以发布你的适配器代码吗?那里的问题与
getChildCount()的使用有关 -
我想这是我用谷歌搜索时不明白的。我唯一的代码是适配器的代码: globalLISTVIEW1.Adapter = new ArrayAdapter
(this, Android.Resource.Layout.SimpleListItem1, mainMENU.ToArray()); -
好吧,有趣。所以 getChildCount() 可能会以某种方式成为问题。老实说,我有点迷失了如何做到这一点。在谷歌上搜索这个问题时,我并没有变得更聪明。
标签: android android-listview android-arrayadapter recycle