【发布时间】:2015-07-24 15:48:34
【问题描述】:
我可能在这里遗漏了一些简单的东西,但我只是看不到它......
所以,我有一个普通的 ListView、一个自定义适配器和一个相对布局。 目前,列表视图中的项目不显示。但是,只要列表视图不在相对布局中(例如:框架布局),自定义适配器就可以工作。另一方面,我可以在相对布局中使用列表视图...只要我不使用自定义适配器。
public class MainActivity : Activity
{
int count = 1;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
ListView list = new ListView (this);
list.SetBackgroundColor (Android.Graphics.Color.Red);
RelativeLayout rl = new RelativeLayout (this);
rl.SetBackgroundColor (Android.Graphics.Color.Blue);
TextView tv = new TextView (this);
tv.Text = "Some text";
tv.SetBackgroundColor (Android.Graphics.Color.Green);
rl.AddView (tv, new RelativeLayout.LayoutParams (400, 100));
List<RelativeLayout> views = new List<RelativeLayout>();
views.Add (rl);
testAdapter adapter = new testAdapter (views, this);
//ArrayAdapter<string> arrayAdapter = new ArrayAdapter<string> (this, Android.Resource.Layout.SimpleListItem1);
//arrayAdapter.Add ("cell 1");
list.Adapter = adapter;
RelativeLayout listContainer = new RelativeLayout (this);
listContainer.AddView (list, new ViewGroup.LayoutParams (400, 600));
listContainer.SetBackgroundColor (Android.Graphics.Color.LightGray);
this.AddContentView (listContainer, new ViewGroup.LayoutParams (ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent));
}
}
class testAdapter:BaseAdapter{
List<RelativeLayout> views = new List<RelativeLayout>();
Android.Content.Context context;
public testAdapter(List<RelativeLayout> inView, Android.Content.Context cntx){
views = inView;
context = cntx;
}
#region implemented abstract members of BaseAdapter
public override Java.Lang.Object GetItem (int position)
{
return position;
}
public override long GetItemId (int position)
{
return position;
}
public override View GetView (int position, View convertView, ViewGroup parent)
{
RelativeLayout temp;
if (convertView != null) {
temp = (RelativeLayout)convertView;
temp.SetBackgroundColor (Android.Graphics.Color.Green);
} else {
temp = new RelativeLayout (context);
}
temp.RemoveAllViews ();
if (position < views.Count) {
RelativeLayout refView = views [position];
View refParent = (View)refView.Parent;
if (refParent != null)
((ViewGroup)refParent).RemoveView (refView);
temp.AddView (refView);
temp.SetBackgroundColor (Android.Graphics.Color.Green);
}
return (View)temp;
}
public override int Count {
get {
return views.Count;
}
}
#endregion
}
此时,我只需要将listContainer 从RelativeLayout 更改为FrameLayout,一切正常。或者我可以保留相对布局并将adapter 更改为我注释掉的arrayAdapter。我知道这是可行的,但我没有使用通常会导致此类问题的任何 wrap content。
其他:getView 返回的单元格永远不会获得任何尺寸。但是,如果我要强制某些尺寸(例如:通过在temp.SetBackgroundColor (Android.Graphics.Color.Green); 下方添加类似temp.LayoutParameters = new AbsListView(300, 100); 的内容)实际上会出现绿色单元格,但不会出现其内容。
【问题讨论】:
-
我正在使用一个自定义 ArrayAdapter ,一个包含 ListView 的 RelativeLayout 以及用于列表每一行的视图都在一个 RelativeLayout 中,一切正常。
temp.RemoveAllViews();在适配器内部做了什么?它有什么用?
标签: android listview xamarin.android