服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Android - android动态布局之动态加入TextView和ListView的方法

android动态布局之动态加入TextView和ListView的方法

2021-03-23 15:50jayqean Android

这篇文章主要介绍了android动态布局之动态加入TextView和ListView的方法,涉及Android动态布局的实现技巧,需要的朋友可以参考下

本文实例讲述了android动态布局之动态加入TextViewListView的方法。分享给大家供大家参考。具体实现方法如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
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 when the activity is first created. */
 @Override
 public void onCreate(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("常用联系人");
  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().toString());
    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);
  // 线性布局 通过参数index控制加入的控件的位置
  // ------------------------
  // 加入分割线
  final TextView line = 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("离线好友");  
  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().toString());
    if(!flag){
     linearLayout.addView(lv2, linearLayout.indexOfChild(tv2) + 1);
     flag = true;
    } else{
     linearLayout.removeView(lv2);
     flag = false;
    }
   }
  });
  linearLayout.addView(tv2, 2);
 }
}

控制布局,可以通过RelativeLayout.LayoutParams类

?
1
2
3
4
5
6
7
final LinearLayout linearLayout = (LinearLayout) findViewById(R.id.groups);
final TextView tv1 = new TextView(this);
tv1.setText("常用联系人");
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); // 线性布局 通过参数index控制加入的控件的位置

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
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 context,
   List<? extends Map<String, ?>> data, int resource, String[] from,
   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 convertView, 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).setChecked((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) data);
      } else {
       setViewImage((ImageView) v, text);
      }
     } else {
      throw new IllegalStateException(
        v.getClass().getName()
          + " is not a "
          + " view that can be bounds by this SimpleAdapter");
     }
    }
   }
  }
 }
 /**
  * Called by bindView() to set the image for an ImageView but only if there
  * is no existing ViewBinder or if the existing ViewBinder cannot handle
  * binding to an ImageView.
  *
  * This method is called instead of {@link #setViewImage(ImageView, String)}
  * if the supplied data is an int or Integer.
  *
  * @param v
  *   ImageView to receive an 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 an ImageView but only if there
  * is no existing ViewBinder or if the existing ViewBinder cannot handle
  * binding to an ImageView.
  *
  * By default, the value will be treated as an image resource. If the value
  * cannot be used as an image resource, the value is used as an image Uri.
  *
  * This method is called instead of {@link #setViewImage(ImageView, int)} if
  * the supplied data is not an int or Integer.
  *
  * @param v
  *   ImageView to receive an image
  * @param value
  *   the value retrieved from the data set
  *
  * @see #setViewImage(ImageView, int)
  */
 public void setViewImage(ImageView v, String value) {
  Bitmap bitMap = BitmapFactory.decodeFile(value);
  v.setImageBitmap(bitMap);
 }
}

下面是friend_info_view.xml

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?xml version="1.0" encoding="UTF-8"?>
<!-- 好友信息列表.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"
   android:adjustViewBounds="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" android:layout_height="wrap_content"
   android:src="@drawable/status_available" android:layout_marginLeft="8.0dip"
   android:layout_marginTop="20.0dip" android:layout_toRightOf="@id/selfImage" />
  <TextView android:id="@+id/setStatus" android:layout_width="wrap_content"
   android:layout_height="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..." />
 <!-- 好友组 点击textview后出现组里的详细好友列表 -->
 <LinearLayout android:id="@+id/groups" android:layout_width="fill_parent"
  android:layout_height="wrap_content" android:orientation="vertical"
 </LinearLayout>
</LinearLayout>

chats_view_item.xml

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?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"
   android: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:id="@+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"
   android: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" />
 </RelativeLayout>
</LinearLayout>

效果图如下:

android动态布局之动态加入TextView和ListView的方法

希望本文所述对大家的Android程序设计有所帮助。

延伸 · 阅读

精彩推荐
  • AndroidAndroid界面效果UI开发资料汇总(附资料包)

    Android界面效果UI开发资料汇总(附资料包)

    android ui界面设计,友好的界面会提高用户体验度;同时也增强了android ui界面设计的难度,本文提供了一些常用开发资料(有下载哦)感兴趣的朋友可以了解下...

    Android开发网4652021-01-03
  • AndroidAndroid中AsyncTask详细介绍

    Android中AsyncTask详细介绍

    这篇文章主要介绍了Android中AsyncTask详细介绍,AsyncTask是一个很常用的API,尤其异步处理数据并将数据应用到视图的操作场合,需要的朋友可以参考下...

    Android开发网7432021-03-11
  • AndroidAndroid实现固定屏幕显示的方法

    Android实现固定屏幕显示的方法

    这篇文章主要介绍了Android实现固定屏幕显示的方法,实例分析了Android屏幕固定显示所涉及的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下...

    鉴客6182021-03-27
  • AndroidAndroid CardView+ViewPager实现ViewPager翻页动画的方法

    Android CardView+ViewPager实现ViewPager翻页动画的方法

    本篇文章主要介绍了Android CardView+ViewPager实现ViewPager翻页动画的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    Abby代黎明9592022-03-02
  • AndroidAndroid实现Service获取当前位置(GPS+基站)的方法

    Android实现Service获取当前位置(GPS+基站)的方法

    这篇文章主要介绍了Android实现Service获取当前位置(GPS+基站)的方法,较为详细的分析了Service基于GPS位置的技巧,具有一定参考借鉴价值,需要的朋友可以参考下...

    Ruthless8332021-03-31
  • Android汇总Android视频录制中常见问题

    汇总Android视频录制中常见问题

    这篇文章主要汇总了Android视频录制中常见问题,帮助大家更好地解决Android视频录制中常见的问题,需要的朋友可以参考下...

    yh_thu5192021-04-28
  • AndroidAndroid程序设计之AIDL实例详解

    Android程序设计之AIDL实例详解

    这篇文章主要介绍了Android程序设计的AIDL,以一个完整实例的形式较为详细的讲述了AIDL的原理及实现方法,需要的朋友可以参考下...

    Android开发网4622021-03-09
  • AndroidAndroid编程解析XML方法详解(SAX,DOM与PULL)

    Android编程解析XML方法详解(SAX,DOM与PULL)

    这篇文章主要介绍了Android编程解析XML方法,结合实例形式详细分析了Android解析XML文件的常用方法与相关实现技巧,需要的朋友可以参考下...

    liuhe68810042021-05-03