在Xamarin Android中将两个适配器添加到一个ListView的方法是通过创建一个自定义适配器来实现。以下是实现此功能的步骤:
public CustomAdapter(Context context, List<string> data1, List<string> data2)
{
this.context = context;
this.data1 = data1;
this.data2 = data2;
}
public override int Count => data1.Count;
public override Java.Lang.Object GetItem(int position)
{
return null;
}
public override long GetItemId(int position)
{
return position;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
View view = convertView;
if (view == null)
{
LayoutInflater inflater = (LayoutInflater)context.GetSystemService(Context.LayoutInflaterService);
view = inflater.Inflate(Android.Resource.Layout.SimpleListItem2, null);
}
TextView text1 = view.FindViewById<TextView>(Android.Resource.Id.Text1);
TextView text2 = view.FindViewById<TextView>(Android.Resource.Id.Text2);
text1.Text = data1[position];
text2.Text = data2[position];
return view;
}
}
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);
listView = FindViewById<ListView>(Resource.Id.listView);
// 初始化数据
data1 = new List<string> { "Item 1", "Item 2", "Item 3" };
data2 = new List<string> { "Description 1", "Description 2", "Description 3" };
// 创建自定义适配器
CustomAdapter adapter = new CustomAdapter(this, data1, data2);
// 设置适配器
listView.Adapter = adapter;
}
}
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
这样,你就可以将两个适配器的数据添加到一个ListView中显示了。自定义适配器中的GetView方法用于设置每个列表项的显示内容,你可以根据自己的需求进行修改。
领取专属 10元无门槛券
手把手带您无忧上云