使用代码动态添加、删除view,通过tag寻找控件

来源:互联网 发布:linux重定向到文件 编辑:程序博客网 时间:2024/05/17 08:04
这个例子是我项目中实际遇到需要,其实,在很久以前就一直想写个动态添加view的东西。。。不过一直没着手来做,这次是项目需要逼得必须做了。。。

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="@drawable/com_no_light_bg"
android:id="@+id/contain"
>
<!-- 加装2G号码 -->

<TextView
android:id="@+id/second_gv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:text="@string/add_2g"
android:textColor="#394A57"
android:textSize="18sp" />

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:background="@drawable/new_add_grid_small_bg"
android:orientation="vertical" >

<GridView
android:id="@+id/add_gv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:horizontalSpacing="3dp"
android:numColumns="3"
android:verticalSpacing="3dp" />

<TextView
android:id="@+id/add_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="月功能费 5元/号/月 2部一上免一部费用"
android:textColor="#00ff00"
android:textSize="13sp" />
</LinearLayout>
<!-- 我有2g号 -->

<CheckBox
android:id="@+id/hasTel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/save_psd_selector"
android:text="我有2G号码"
android:textColor="@android:color/black"
android:textSize="15sp" >
</CheckBox>

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/body"
>

</LinearLayout>
</LinearLayout>

grid_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/grid_relative"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:background="@drawable/grid_item_bg" >

<ImageView
android:id="@+id/img_checked"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/green_checked" />

<TextView
android:id="@+id/grid_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="3dp"
android:layout_toRightOf="@+id/img_checked"
android:text="286元套餐"
android:textColor="#000000"
android:textSize="11sp" />

</RelativeLayout>

add_tel.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/add_2g_tel"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:layout_marginTop="3dp"
android:orientation="vertical"
>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
>

<TextView
android:id="@+id/tv01"
android:layout_width="60dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="3dp"
android:gravity="center_vertical"
android:text="2G手机号1"
android:textColor="#000000" />

<Button
android:id="@+id/send_auth_code_one"
android:layout_width="83dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="3dp"
android:text="@string/businessprocess_fasongyanzhengma"
android:textSize="12sp" />

<EditText
android:id="@+id/tel_2g_num_one"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/send_auth_code_one"
android:layout_toRightOf="@id/tv01"
android:inputType="phone"
android:maxLength="11"
android:singleLine="true"
android:text="12345678912"
android:textColor="#000000" />
</RelativeLayout>

<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>

<ImageView
android:id="@+id/add_2g_one"
android:layout_width="60dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="3dp"
android:src="@drawable/add_telephone_number"
android:visibility="invisible"
/>

<Button
android:id="@+id/confirm_one"
android:layout_width="83dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="3dp"
android:text="@string/ok"
android:textSize="12sp" />

<EditText
android:id="@+id/auth_code_one"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toLeftOf="@id/confirm_one"
android:layout_toRightOf="@id/add_2g_one"
android:clickable="false"
android:inputType="phone"
android:maxLength="11"
android:singleLine="true"
android:text="12345678912"
android:textColor="#000000" />
</RelativeLayout>

</LinearLayout>

主Activity:

package test.dongtai;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
/**
* 动态添加、移除view
*
* @author huanghaifeng
*
* @version 2012.06.15
*
*/
public class TestDongtaiActivity extends Activity {
/** Called when the activity is first created. */
private final static int VIEW = 0;
private final static int SEND = 1;
private final static int OK = 2;
private final static int ADD = 3;
private final static int AUTH_CODE = 4;
private final static int TEL = 5;
private final static int LABEL = 6;

/**
*前四个是页面状态
*后三个是点击按钮
*/
private enum State{
NORMAL,
DELETE,
NEW,
ADD,
OK,
SEND
}

private CheckBox mCheckBox;
private LinearLayout body;
private GridView add_gv;
private GridRadioAdapter addApdater;

private List<State> stateList = new ArrayList<State>();
private List<Map<String,Object>> twoList = new ArrayList<Map<String,Object>>();

private int addCount = 3;
private int addViewId = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

body = (LinearLayout) this.findViewById(R.id.body);

mCheckBox = (CheckBox) this.findViewById(R.id.hasTel);
mCheckBox.setOnCheckedChangeListener(checkedChangeListener);

add_gv = (GridView)findViewById(R.id.add_gv);
add_gv.setSelector(new ColorDrawable(Color.TRANSPARENT));// 设置系统自带选中背景为透明的

loadData();

addCount = Integer.parseInt(twoList.get(0).get("count").toString());

addApdater = new GridRadioAdapter(this, twoList, 0, false, 4);
add_gv.setAdapter(addApdater);

add_gv.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
addApdater.changeState(position);
int temp = addCount;
addCount = Integer.parseInt(twoList.get(position).get("count").toString());
if(addCount > temp){//如果点击的个数比原来的大
if(stateList.size() != 0 && stateList.get(body.getChildCount()-1) == State.DELETE){//当为delete状态时,显示加号
if(addViewId < addCount * 10){
View lastView = body.getChildAt(body.getChildCount()-1);
ImageView add1 = (ImageView) lastView.findViewById(R.id.add_2g_one);
add1.setImageResource(R.drawable.add_telephone_number);
add1.setVisibility(View.VISIBLE);
stateList.set(body.getChildCount()-1, State.ADD);
}
}
}else if(addCount < temp){//如果点击的个数比原来的小
if(stateList.size() != 0 && stateList.get(body.getChildCount()-1) == State.ADD){//当为add状态时,隐藏
if(addViewId >= addCount * 10){
View lastView = body.getChildAt(body.getChildCount()-1);
ImageView add1 = (ImageView) lastView.findViewById(R.id.add_2g_one);
add1.setVisibility(View.GONE);
stateList.set(body.getChildCount()-1, State.DELETE);
}
}
}
System.out.println("stateList state = " + stateList);
}
});
}

private void loadData(){
Map<String,Object> map = new HashMap<String, Object>();
map.put("name", "1部");
map.put("count", "1");
twoList.add(map);
map = new HashMap<String, Object>();
map.put("name", "2部");
map.put("count", "2");
twoList.add(map);
map = new HashMap<String, Object>();
map.put("name", "3部");
map.put("count", "3");
twoList.add(map);
map = new HashMap<String, Object>();
map.put("name", "4部");
map.put("count", "4");
twoList.add(map);
map = new HashMap<String, Object>();
map.put("name", "5部");
map.put("count", "5");
twoList.add(map);
}

private void addDiyView(){
addViewId += 10;
View view = LayoutInflater.from(TestDongtaiActivity.this).inflate(R.layout.add_tel, null);

setDiyViewTag(view,addViewId,false);

body.setVisibility(View.VISIBLE);
body.addView(view);
}

private void setDiyViewTag(View view,int addViewTag,boolean isDelete){
view.setTag(addViewTag + VIEW + "");

Button send = (Button) view.findViewById(R.id.send_auth_code_one);
send.setTag(addViewTag + SEND + "");
send.setOnClickListener(addViewClickListener);

Button ok = (Button) view.findViewById(R.id.confirm_one);
ok.setTag(addViewTag + OK + "");
ok.setOnClickListener(addViewClickListener);

ImageView add = (ImageView) view.findViewById(R.id.add_2g_one);
add.setTag(addViewTag + ADD + "");

if(addViewTag == 10){
if(!isDelete){
stateList.add(Integer.parseInt(view.getTag().toString().substring(0, view.getTag().toString().length()-1))-1, State.NORMAL);
add.setVisibility(View.INVISIBLE);
}else{
if(stateList.get(body.getChildCount()-1) == State.DELETE){
add.setVisibility(View.GONE);
}else{
add.setVisibility(View.INVISIBLE);
}
}
}else{
if(!isDelete){
stateList.add(Integer.parseInt(view.getTag().toString().substring(0, view.getTag().toString().length()-1))-1, State.NEW);
add.setVisibility(View.VISIBLE);
add.setImageResource(R.drawable.hide_telephone_number);
}else{
if(stateList.get(body.getChildCount()-1) == State.DELETE){
add.setVisibility(View.GONE);
}else{
add.setVisibility(View.VISIBLE);
add.setImageResource(R.drawable.hide_telephone_number);
}
}
}
add.setOnClickListener(addViewClickListener);

EditText auth_code = (EditText) view.findViewById(R.id.auth_code_one);
auth_code.setTag(addViewTag + AUTH_CODE + "");

EditText tel = (EditText) view.findViewById(R.id.tel_2g_num_one);
tel.setTag(addViewTag + TEL + "");

TextView label = (TextView) view.findViewById(R.id.tv01);
label.setText(getResources().getString(R.string.i_have_two)+addViewTag/10);
label.setTag(addViewTag + LABEL + "");

System.out.println("ADD stateList state = " + stateList);
}

/**
*
* @param state 点击的按钮
* @param viewId 要添加的view 的id
*/
private void viewState(State state,int viewId){
switch(state){
case ADD://点击加号之后需要将加号隐藏
if(stateList.get(viewId-1) == State.ADD){
Toast.makeText(TestDongtaiActivity.this, "增加号码"+viewId, 0).show();
ImageView add1 = (ImageView) body.findViewWithTag(viewId + String.valueOf(ADD));
add1.setVisibility(View.GONE);
stateList.set(viewId-1, State.DELETE);
addDiyView();
}else{
Toast.makeText(TestDongtaiActivity.this, "删除未输入布局"+viewId, 0).show();
View view = body.findViewWithTag(viewId + String.valueOf(VIEW));
body.removeView(view);
addViewId -= 10;
stateList.remove(viewId-1);

if(addViewId != 0 && addViewId < addCount * 10){
View lastView = body.getChildAt(body.getChildCount()-1);
ImageView add1 = (ImageView) lastView.findViewById(R.id.add_2g_one);
add1.setImageResource(R.drawable.add_telephone_number);
add1.setVisibility(View.VISIBLE);
stateList.set(body.getChildCount()-1, State.ADD);
}
}
break;
case OK:
EditText tel = (EditText) body.findViewWithTag(viewId + String.valueOf(TEL));
tel.setFocusable(false);

Button send = (Button) body.findViewWithTag(viewId + String.valueOf(SEND));
send.setText(getResources().getString(R.string.delete));

EditText auth_code = (EditText) body.findViewWithTag(viewId + String.valueOf(AUTH_CODE));
auth_code.setVisibility(View.GONE);

Button ok = (Button) body.findViewWithTag(viewId + String.valueOf(OK));
ok.setVisibility(View.GONE);

ImageView add = (ImageView) body.findViewWithTag(viewId + String.valueOf(ADD));

Log.i("Dongtai", "addViewId = " + addViewId +",addCount = " + addCount);

if(addViewId >= addCount * 10){//如果是最后一个,则不显示加号
add.setVisibility(View.GONE);
stateList.set(viewId-1, State.DELETE);
}else{
add.setVisibility(View.VISIBLE);
add.setImageResource(R.drawable.add_telephone_number);
stateList.set(viewId-1, State.ADD);
System.out.println("viewId = " + viewId);
}

System.out.println("OK stateList state = " + stateList);
break;
case SEND://发送验证码和删除公用一个
if(stateList.get(viewId-1) == State.NORMAL || stateList.get(viewId-1) == State.NEW){
//发送验证码
Toast.makeText(TestDongtaiActivity.this, "发送验证码"+viewId, 0).show();
}else{//删除
Toast.makeText(TestDongtaiActivity.this, "删除"+viewId, 0).show();
View view = body.findViewWithTag(viewId + String.valueOf(VIEW));
body.removeView(view);
addViewId -= 10;
stateList.remove(viewId-1);
//重新设置被删除位置后的view tag
for(int i = (viewId-1);i < body.getChildCount();i++){
View tempView = body.getChildAt(i);
setDiyViewTag(tempView, (i+1)*10,true);
}

if(addViewId != 0 && addViewId < addCount * 10){
View lastView = body.getChildAt(body.getChildCount()-1);
ImageView add1 = (ImageView) lastView.findViewById(R.id.add_2g_one);
add1.setImageResource(R.drawable.add_telephone_number);
add1.setVisibility(View.VISIBLE);
stateList.set(body.getChildCount()-1, State.ADD);
}else if(addViewId >= addCount * 10 && stateList.get(body.getChildCount()-1) == State.NEW){
View lastView = body.getChildAt(body.getChildCount()-1);
ImageView add1 = (ImageView) lastView.findViewById(R.id.add_2g_one);
add1.setVisibility(View.INVISIBLE);
stateList.set(body.getChildCount()-1, State.NORMAL);
}
System.out.println("DELETE stateList state = " + stateList);
}
break;
}
}

private OnCheckedChangeListener checkedChangeListener = new OnCheckedChangeListener() {

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
addDiyView();
}else{
addViewId = 0;
stateList.clear();
body.removeAllViews();

}
Log.i("Dongtai", "addCount = " + addViewId);
}
};

public OnClickListener addViewClickListener = new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String tag = v.getTag().toString();
System.out.println("Tag = " + tag);
int viewId = Integer.parseInt(tag.substring(0, tag.length()-1));
int subId = Integer.parseInt(tag.substring(tag.length()-1, tag.length()));
switch(subId){
case 1:
viewState(State.SEND,viewId);
break;
case 2:
viewState(State.OK, viewId);
Toast.makeText(TestDongtaiActivity.this, "确认" + tag.substring(0, tag.length()-1), 0).show();
break;
case 3:
viewState(State.ADD, viewId);
break;
}
}
};
}

GridRadioAdapter.java

package test.dongtai;

import java.util.List;
import java.util.Map;
import java.util.Vector;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class GridRadioAdapter extends BaseAdapter
{
private Context mContext; // 定义Context
// private Vector<Integer> mImageIds = new Vector<Integer>(); // 定义????向量作为图片??
private Vector<Boolean> mImage_bs = new Vector<Boolean>(); // 定义????向量作为选中与否容器
private List<Map<String, Object>> gridTextList;

private int lastPosition = -1; // 记录上一次??中的图片位置??1表示未??中任何图??
private boolean multiChoose; // 表示当前适配器是否允许多??
private int flag = 0;// 0:套??1:首月资??2:业务包 3:优??

private LayoutInflater inflate;

/**
*
* @param c
* 上下??
* @param gridTextList
* 填充数据
* @param index
* 默认选中位置 -1为什么都不??
* @param isMulti
* 是否为多??true多??,false单??
* @param flag
* 0:套餐,1:首月资费,2:可选业务包??:优??4:合约计划??首月资费、可选优惠??可??业务包??套餐 5:合约计划??
* 绑定套餐计划
*/
public GridRadioAdapter(Context c, List<Map<String, Object>> gridTextList, int index, boolean isMulti, int flag)
{
mContext = c;
multiChoose = isMulti;
this.gridTextList = gridTextList;
inflate = LayoutInflater.from(mContext);
lastPosition = index;
this.flag = flag;

// System.out.println("gridTextList = " + gridTextList);

// 装入资源
for (int i = 0; i < gridTextList.size(); i++)
{
if (i == lastPosition)
{
mImage_bs.add(true);
} else
{
mImage_bs.add(false);
}
}
}

@Override
public int getCount()
{
// TODO Auto-generated method stub
// System.out.println("gridTextList list = " + gridTextList);
// System.out.println("gridTextList size = " + gridTextList.size());
return gridTextList.size();
}

@Override
public Object getItem(int position)
{
// TODO Auto-generated method stub
return position;
}

@Override
public long getItemId(int position)
{
// TODO Auto-generated method stub
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
// System.out.println("===============GETVIEW getview===position======================="+position);
ViewHolder holder;
if (convertView == null)
{
holder = new ViewHolder();
convertView = inflate.inflate(R.layout.grid_item, null);
holder.grid_iv = (ImageView) convertView.findViewById(R.id.img_checked);
holder.grid_tv = (TextView) convertView.findViewById(R.id.grid_text);
holder.grid_ll = (RelativeLayout) convertView.findViewById(R.id.grid_relative);
convertView.setTag(holder);
} else
{
holder = (ViewHolder) convertView.getTag();
}

if (mImage_bs.elementAt(position))
{
holder.grid_iv.setVisibility(View.VISIBLE);
holder.grid_ll.setBackgroundResource(R.drawable.new_add_item_bg_2);
} else
{
holder.grid_iv.setVisibility(View.GONE);
holder.grid_ll.setBackgroundResource(R.drawable.new_add_item_bg_1);
}
String obj = "";
switch (flag)
{
case 0:
obj = gridTextList.get(position).get("PACKAGE_NAME").toString();
break;
case 1:
obj = gridTextList.get(position).get("FIRSTMONPRICE_NAME").toString();
break;
case 2:
obj = gridTextList.get(position).get("BUSINESSPACKAGE_NAME").toString();
break;
case 3:
obj = gridTextList.get(position).get("PROMOTIONS_NAME").toString();
break;
case 4:
obj = gridTextList.get(position).get("name").toString();
break;
case 5:
obj = gridTextList.get(position).get("TYPE_VALUE").toString();
break;
case 6:
obj = gridTextList.get(position).get("planname").toString();
break;
case 7:
obj = gridTextList.get(position).get("rulename").toString();
break;
case 8:
obj = gridTextList.get(position).get("planname").toString()
+ gridTextList.get(position).get("calltime").toString()
+ gridTextList.get(position).get("bandwidth").toString();
break;
}

holder.grid_tv.setText(obj);
// System.out.println("===============getview===position======================="+position);

return convertView;
}

private LayerDrawable makeBmp(int id, boolean isChosen)
{
Bitmap mainBmp = ((BitmapDrawable) mContext.getResources().getDrawable(id)).getBitmap();

// 根据isChosen来??取对勾的图片
Bitmap seletedBmp = null;
if (isChosen == true)
seletedBmp = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.checkbox_checked);
else
seletedBmp = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.checkbox_unchecked);

// 产生叠加??
Drawable[] array = new Drawable[2];
array[0] = new BitmapDrawable(mainBmp);
array[1] = new BitmapDrawable(seletedBmp);
LayerDrawable la = new LayerDrawable(array);
la.setLayerInset(0, 0, 0, 0, 0);
la.setLayerInset(1, 0, -5, 60, 45);

return la; // 返回叠加后的??
}

// 修改选中的状??
public void changeState(int position)
{
// 多????
if (multiChoose == true)
{
if (position == gridTextList.size() - 1)
{// 当??择的是最后一项时,取??其他选中状??
// mImage_bs.setElementAt(true,position);
for (int i = 0; i < gridTextList.size() - 1; i++)
{
mImage_bs.setElementAt(false, i);
}
} else
{

mImage_bs.setElementAt(false, gridTextList.size() - 1);
}
mImage_bs.setElementAt(!mImage_bs.elementAt(position), position); // 直接取反即可
}
// 单????
else
{

if (position != -1)
{
if (lastPosition != -1)
{
mImage_bs.setElementAt(false, lastPosition); // 取消上一次的选中状??
}
mImage_bs.setElementAt(!mImage_bs.elementAt(position), position); // 直接取反即可
lastPosition = position; // 记录本次选中的位??
} else
{
// System.out.println("Position = " + position);
for (int i = 0; i < gridTextList.size(); i++)
{
mImage_bs.setElementAt(false, i);
// System.out.println("mImage_bs = " + mImage_bs);
}
}
}
notifyDataSetChanged(); // 通知适配器进行更??
}

/**
* 返回选中与否容器
*
* @author
*/
public Vector<Boolean> getSelectedVector()
{
return mImage_bs;

}

class ViewHolder
{
public TextView grid_tv;
public ImageView grid_iv;
public RelativeLayout grid_ll;
}
}




      
原创粉丝点击