本文实例讲述了android动态布局之动态加入TextView和ListView的方法。分享给大家供大家参考。具体实现方法如下:
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> data = new ArrayList>();
Map map = new HashMap();
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