为了说明我的想法:一个非常基本的示例项目就像提示用户输入一个数字,而不是使用'for'循环显示Hello World数字时间。是否有可能使用适配器来实现这一点,或者我应该寻找更好的选择?
是的,可以使用适配器完成此操作。但不能与默认的适配器,但有一个自定义适配器象下面这样:
public class MyListAdapter : Java.Lang.Object,IListAdapter
{
public int Count {
get {
//list view will show 10 lines of data
return 10;
}
}
public bool HasStableIds { get { return false; } }
public bool IsEmpty { get { return false; } }
public int ViewTypeCount { get { return 1; } }
private Context context;
private string uniqueData;
//default constructor
public MyListAdapter()
{ }
//constructor with current context and the data you want to show in your listview
public MyListAdapter(Context c,string data)
{
context = c;
uniqueData = data;
}
public bool AreAllItemsEnabled()
{
return true;
}
public void Dispose()
{
this.Dispose();
}
public Java.Lang.Object GetItem(int position)
{
throw new NotImplementedException();
}
public long GetItemId(int position)
{
return 0;
}
public int GetItemViewType(int position)
{
return 1;
}
public View GetView(int position, View convertView, ViewGroup parent)
{
View et=convertView;
if (et == null)
{
et = new TextView(context);
(et as TextView).Text = uniqueData;
}
return et;
}
public bool IsEnabled(int position)
{
return true;
}
public void RegisterDataSetObserver(DataSetObserver observer)
{
}
public void UnregisterDataSetObserver(DataSetObserver observer)
{
}
}
正如你所看到的,Count.get
返回你的ListView的循环次数,并在GetView
我创建了一个TextView
程序,这需要字符串数据由构造函数传递。
这样我可以用它象下面这样:
public class MainActivity : Activity
{
ListView myListView;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
myListView = FindViewById<ListView>(Resource.Id.MyListView);
myListView.Adapter=new MyListAdapter(this,"this is my custom data");
}
}
谢谢,这看起来整洁!如果我有几个UI元素,也可以使用类似的东西,对吗?在这种情况下,数据端将是一个集合(一个数组或一个列表等),并且UI将具有一些TextView或Buttons。 – rTECH
如果您有几个UI元素,则需要更改被覆盖的'GetView'方法。你可以参考[这个文档](http://www.vogella.com/tutorials/AndroidListView/article.html#adapterown)。它没有使用“IListAdapter”。但这个想法是一样的。 –