Advertisement
manski

Create custom list adaptor in MonoDroid

Jul 4th, 2012
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.77 KB | None | 0 0
  1. ListView view = new ListView(this);
  2. MyAdapter adapter = new MyAdapter(this);
  3. view.Adapter = adapter;
  4. mainLayout.AddView(view);
  5.  
  6. adapter.Add("111");
  7. adapter.Add("222");
  8. adapter.Add("333");
  9. adapter.Add("444");
  10.  
  11.  
  12. private class MyAdapter : ArrayAdapter<string> {
  13.   private int m_preferredListHeight = -1;
  14.  
  15.   public MyAdapter(Context ctx) : base(ctx, 0) { }
  16.  
  17.   public override View GetView(int position, View convertView, ViewGroup parent) {
  18.     LinearLayout layout = new LinearLayout(this.Context) { Orientation = Orientation.Horizontal };
  19.    
  20.     ImageView icon = new ImageView(this.Context);
  21.     icon.SetImageDrawable(this.Context.Resources.GetDrawable(Resource.Drawable.icon_large));
  22.     icon.SetAdjustViewBounds(true);
  23.     icon.SetMaxHeight(GetPreferredListHeight());
  24.     layout.AddView(icon);
  25.  
  26.     TextView text = new TextView(this.Context);
  27.     text.Text = GetItem(position);
  28.     layout.AddView(text);
  29.    
  30.     return layout;
  31.   }
  32.  
  33.   private int GetPreferredListHeight() {
  34.     if (this.m_preferredListHeight == -1) {
  35.       TypedValue typedValue = new TypedValue(); //create a new typed value to received the resolved attribute value
  36.       DisplayMetrics displayMetrics = this.Context.Resources.DisplayMetrics;
  37.       int resId = Android.Resource.Attribute.ListPreferredItemHeight;
  38.       if (!this.Context.Theme.ResolveAttribute(resId, typedValue, true)) {
  39.         throw new ArgumentException("Resource ID #" + resId);
  40.       }
  41.  
  42.       if (typedValue.Type != DataType.Dimension) {
  43.         throw new ArgumentException("Resource ID #" + resId + " type " + typedValue.Type + " is not valid");
  44.       }
  45.  
  46.       this.m_preferredListHeight = TypedValue.ComplexToDimensionPixelSize(typedValue.Data, displayMetrics);
  47.     }
  48.  
  49.     return this.m_preferredListHeight;
  50.   }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement