Dynamically adding TextView and ListView to Android dynamic layouts _android

Source: Internet
Author: User
Tags gettext stub

This example describes the dynamic addition of Android dynamic layouts to TextView and ListView. Share to everyone for your reference. The implementation method is as follows:

Package Org.guoshi; 
Import java.util.ArrayList; 
Import Java.util.HashMap; 
Import java.util.List; 
Import Java.util.Map; 
Import Org.guoshi.adapter.ImageAndTextAdapter; 
Import android.app.Activity; 
Import Android.graphics.Color; 
Import Android.os.Bundle; 
Import Android.util.Log; 
Import Android.view.View; 
Import Android.view.View.OnClickListener; 
Import Android.view.ViewGroup.LayoutParams; 
Import Android.widget.LinearLayout; 
Import Android.widget.ListAdapter; 
Import Android.widget.ListView; 
Import Android.widget.RelativeLayout; 
Import Android.widget.TextView; public class Main extends activity {/** called ' the Activity ' is a/a @Override public void oncreat 
  E (Bundle savedinstancestate) {super.oncreate (savedinstancestate);  
  Setcontentview (R.layout.friend_info_view); 
  Final LinearLayout linearlayout = (linearlayout) Findviewbyid (r.id.groups); 
  Final ListView LV = new ListView (this); list<map<string, object>> data = new ArraylIst<map<string, object>> (); 
  map<string, object> map = new hashmap<string, object> (); 
  Map.put ("title", "Jayqean"); 
  Map.put ("Imgsrc", R.drawable.icon); 
  Data.add (map);  ListAdapter adapter = new Imageandtextadapter (main.this, data, R.layout.chats_view_item, new string[] {"title", "Imgsrc" 
  }, new int[] {r.id.chats_view_name, r.id.chats_view_item_image}); 
  Lv.setadapter (adapter); 
  Final TextView TV1 = new TextView (this); 
  Tv1.settext ("common contact"); 
  Tv1.setid (1); Final Relativelayout.layoutparams LP1 = new Relativelayout.layoutparams (layoutparams.fill_parent, LayoutParams.WRAP_ 
  CONTENT); 
  Lp1.addrule (Relativelayout.below, r.id.groups); 
  Tv1.setlayoutparams (LP1); 
  Tv1.setbackgroundcolor (R.color.group_view_background); 
   Tv1.setonclicklistener (New Onclicklistener () {Boolean flag = false; @Override public void OnClick (View v) {//TODO auto-generated Method stub log.d ("tag", Tv1.gettext (). Tostri 
    Ng ()); If(!flag) 
{Linearlayout.addview (LV, linearlayout.indexofchild (TV1) + 1); 
Lp1.addrule (Relativelayout.below, 1); 
     Linearlayout.addview (LV, LP1); 
    Flag = true; 
     } else{Linearlayout.removeview (LV); 
    Flag = false; 
  } 
   } 
  });
  Linearlayout.addview (TV1, LP1); 
  The linear layout controls the position of the added control through the parameter index//------------------------//Add the Split line final TextView lines = new TextView (this); 
  Line.setlayoutparams (New Layoutparams (Layoutparams.fill_parent, 1)); 
  Line.setbackgroundcolor (Color.White); 
  Linearlayout.addview (line, 1); 
  ------------------------final ListView Lv2 = new ListView (this); 
  list<map<string, object>> data2 = new arraylist<map<string, object>> (); 
  map<string, object> map2 = new hashmap<string, object> (); 
  Map2.put ("title", "Xiaobei"); 
  Map2.put ("Imgsrc", R.drawable.icon); 
  Data2.add (MAP2); ListAdapter adapter2 = new Imageandtextadapter (Main.this, data2, R.layout.chats_view_iteM, new string[] {"title", "Imgsrc"}, new int[] {r.id.chats_view_name, r.id.chats_view_item_image}); 
  Lv2.setadapter (ADAPTER2); 
  Final TextView TV2 = new TextView (this);   
  Tv2.settext ("Offline Friends"); 
  Tv2.setlayoutparams (New Layoutparams (Layoutparams.fill_parent, layoutparams.wrap_content)); 
  Tv2.setbackgroundcolor (R.color.group_view_background); 
   Tv2.setonclicklistener (New Onclicklistener () {Boolean flag = false; @Override public void OnClick (View v) {//TODO auto-generated Method stub log.d ("tag", Tv2.gettext (). Tostri 
    Ng ()); 
     if (!flag) {Linearlayout.addview (Lv2, Linearlayout.indexofchild (TV2) + 1); 
    Flag = true; 
     } else{Linearlayout.removeview (LV2); 
    Flag = false; 
  } 
   } 
  }); 
 Linearlayout.addview (TV2, 2); }
}

Control layout, you can pass the Relativelayout.layoutparams class

Final LinearLayout linearlayout = (linearlayout) Findviewbyid (r.id.groups);
Final TextView TV1 = new TextView (this);
Tv1.settext ("common Contact");
Relativelayout.layoutparams LP1 = new Relativelayout.layoutparams (layoutparams.fill_parent, LayoutParams.WRAP_ CONTENT);
Lp1.addrule (Relativelayout.below, r.id.groups);
Tv1.setlayoutparams (LP1);
Linearlayout.addview (TV1, LP1);

Linearlayout.addview (TV1, 0) can also be used; Linear layout controls The position of the added control by parameter index

Package org.guoshi.adapter; 
Import java.util.List; 
Import Java.util.Map; 
Import Android.content.Context; 
Import Android.graphics.Bitmap; 
Import Android.graphics.BitmapFactory; 
Import Android.util.Log; 
Import Android.view.LayoutInflater; 
Import Android.view.View; 
Import Android.view.View.OnClickListener; 
Import Android.view.ViewGroup; 
Import android.widget.Checkable; 
Import Android.widget.ImageView; 
Import Android.widget.SimpleAdapter; 
Import Android.widget.TextView; 
 public class Imageandtextadapter extends Simpleadapter {private context mcontext; 
 Private int[] MTo; 
 Private string[] Mfrom; 
 Private Viewbinder Mviewbinder; Private list<? 
 Extends Map<string,?>> Mdata; 
 private int mresource; 
 Private Layoutinflater Minflater; Public Imageandtextadapter (context, list<? extends Map<string,?>> data, int resource, string[] fr 
  OM, int[] to} {Super (context, data, resource, from, to); 
  Mcontext = context; Mdata = DatA 
  Mresource = resource; 
  Mfrom = from; 
  MTo = to; 
Minflater = (layoutinflater) context. Getsystemservice (Context.layout_inflater_service); 
 Minflater = Layoutinflater.from (Mcontext); }/** * @see android.widget.adapter#getview (int, view, viewgroup)/public view GetView (int position, view conv 
 Ertview, ViewGroup parent) {return Createviewfromresource (position, Convertview, parent, mresource); 
  Private view Createviewfromresource (int position, View Convertview, viewgroup parent, int resource) {view V; 
   if (Convertview = = null) {v = minflater.inflate (resource, parent, false); 
   Final int[] to = mTo; 
   Final int count = To.length; 
   Final view[] holder = new View[count]; 
   for (int i = 0; i < count; i++) {Holder[i] = V.findviewbyid (to[i)); 
  } v.settag (holder); 
  else {v = convertview; 
} bindview (position, v); 
Final int index = position;   V.setonclicklistener (New Onclicklistener () {//
public void OnClick (View v) {////TODO auto-generated Method Stub//LOG.D ("item", Index + ""); 
  //   } 
//  }); 
 return v; 
  } private void BindView (int position, view view) {Final map<string,?> dataSet = mdata.get (position); 
  if (DataSet = null) {return; 
  Final Viewbinder binder = Mviewbinder; 
  Final view[] Holder = (view[]) View.gettag (); 
  Final string[] from = Mfrom; 
  Final int[] to = mTo; 
  Final int count = To.length; 
   for (int i = 0; i < count; i++) {final View v = holder[i]; 
    if (v!= null) {final Object data = Dataset.get (From[i]); String Text = data = null? 
    "": data.tostring (); 
    if (text = = null) {text = ""; 
    Boolean bound = false; 
    if (binder!= null) {bound = Binder.setviewvalue (V, data, text); } if (!bound) {if (v instanceof checkable) {if (data instanceof Boolean) {(checkable) v). Set 
      Checked ((Boolean) data); 
  } else {     throw new IllegalStateException (V.getclass (). GetName () + "should be bound to a Boolean, not a" 
      + Data.getclass ()); 
     ' Else if ' (v instanceof TextView) {setviewtext (TextView) v, text); else if (v instanceof imageview) {if (data instanceof Integer) {setviewimage ((ImageView) v, (Integer) d 
      ATA); 
      else {setviewimage (ImageView) v, text); 
          } else {throw new IllegalStateException (V.getclass (). GetName () + "not a" 
     + "view that can is bounds by this simpleadapter"); }}}/** * called by BindView () to set the "image for a imageview but only if there * are no exi 
  Sting Viewbinder or if the existing viewbinder cannot handle * binding to a imageview. * * This are called instead of {@link #setViewImage (ImageView, String)} * If the supplied data is a int or in 
  Teger.   * * @param v *ImageView to receive a image * @param value * The value retrieved from the data set * * @see #setViewImage ( 
 ImageView, String) */public void Setviewimage (ImageView v, int value) {V.setimageresource (value);  }/** * Called by BindView () to set the image for a imageview but only if there * are no existing viewbinder or if 
  The existing viewbinder cannot handle * binding to a imageview. * By default, the value is treated as an image resource. 
  If the value * cannot be used as a image resource, the value is used as an image Uri. * * This is called instead of {@link #setViewImage (imageview, int)} if * The supplied data are not a int or I 
  Nteger. 
  * * @param v * ImageView to receive a image * @param value * The value retrieved from the data set * * @see #setViewImage (imageview, int) */public void Setviewimage (ImageView V, String value) {Bitmap Bitmap = Bi 
  Tmapfactory.decodefile (value); V.sEtimagebitmap (BITMAP); } 
}

The following is Friend_info_view.xml

<?xml version= "1.0" encoding= "UTF-8"?> <!--buddy Information list. xml--> <linearlayout xmlns:android= "Http://schemas . android.com/apk/res/android "android:orientation=" vertical "android:layout_width=" fill_parent "Android:layout_ 
  height= "Fill_parent" android:background= "#ffffff" > <relativelayout android:layout_width= "wrap_content" android:layout_height= "Wrap_content" > <imageview android:id= "@+id/selfimage" true "Android:layout_width=" @dimen/self_image_width "android:layout_height=" @dimen/self_image_height "Android:layout_ marginleft= "5.0dip" android:layout_marginbottom= "10.0dip" android:layout_margintop= "3.0dip" android:src= "@ Drawable/default_image "/> <imageview android:id=" @+id/currentstatus "android:layout_width=" Wrap_content "and roid:layout_height= "Wrap_content" android:src= "@drawable/status_available" android:layout_marginleft= "8.0dip" and roid:layout_margintop= "20.0dip" android:layout_torightof= "@id/selfimage "/> <textview android:id=" @+id/setstatus "android:layout_width=" Wrap_content "Android:layout_he" ight= "Wrap_content" android:layout_margintop= "20.0dip" android:layout_marginleft= "8.0dip" android:text= "Tap here to Set your status "android:layout_torightof=" @+id/currentstatus/> </RelativeLayout> <edittext android: Id= "@+id/searchfriend" android:adjustviewbounds= "true" android:layout_height= "50dip" android:layout_width= "Fill_" Parent "android:text=" Search ... "/> <!--buddy Group Click TextView after the group's detailed buddy list--> <linearlayout android:id=" @+id/gro Ups "Android:layout_width=" fill_parent "android:layout_height=" wrap_content "android:orientation=" vertical "> &L T;/linearlayout> </LinearLayout>

Chats_view_item.xml

<?xml version= "1.0" encoding= "UTF-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/" Android "android:orientation=" vertical "android:layout_width=" fill_parent "android:layout_height=" Fill_parent " android:background= "@color/white" > <relativelayout android:id= @+id/chats_view_item "Android:layout_width=" Wrap_content "android:layout_height=" wrap_content "> <imageview android:id=" @+id/chats_view_item_image "Andro" Id:layout_width= "@dimen/friend_image_width" android:layout_height= "@dimen/friend_image_height" Android: paddingleft= "5.0dip" android:paddingtop= "2.0dip" android:src= "@drawable/default_image"/> <textview android:i D= "@+id/chats_view_name" android:textsize= "14.0sp" android:paddingleft= "10.0dip" android:textstyle= "Bold" Android: Ellipsize= "marquee" android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:text= " Username "android:singleline=" true "android:paddingtop=" 2.0dip"android:layout_torightof=" @+id/chats_view_item_image "/> <imageview android:id=" @+id/friend_status_icon " Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:paddingleft= "10.0dip" Android: paddingtop= "1.0dip" android:layout_below= "@+id/chats_view_name" android:layout_torightof= "@+id/chats_view_item_ Image "Android:src=" @drawable/jabber_available "/> <textview android:id=" @+id/chats_view_status "Android: Textcolor= "@android: Color/secondary_text_light" android:ellipsize= "marquee" android:layout_width= "Fill_parent" an droid:layout_height= "Wrap_content" android:text= "available" android:singleline= "true" android:paddingleft= "2.0dip "Android:layout_torightof=" @+id/friend_status_icon "android:layout_below=" @+id/chats_view_name "/> </Rela Tivelayout> </LinearLayout>

The effect chart is as follows:

I hope this article will help you with your Android program.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.