Android中动态添加view,删除view,获取view的内容

动态添加删除红包使用条件
本文介绍了一种在Android应用中动态添加和删除红包使用条件的方法,并提供了详细的代码实现。该方案利用布局的addview和removeview方法进行操作,同时通过HashMap管理条件数据,便于后期数据提交。

最近在项目中碰到一个需求,在编辑一个红包详情页面的时候,需要动态的添加使用条件,并且可以删除,最后提交数据的时候需要获取到条件里面的数据。网上搜了一些答案没有比较满意的解决方法,所以写下此文。

效果图:


解决思路:

1.使用布局的addview方法,即可动态添加。

2.动态删除需要获取到当前条目在布局中的位置或者对象,然后用removeview方法删除。

3.提交服务器需要获取条目中的数据,可以通过维护一个hashmap集合来遍历获取其中的内容。

废话不多说了,上代码!

1.先上item的布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="51dp"
    android:id="@+id/ll_condition_edit_redbag2"
    android:orientation="vertical">



    <LinearLayout

        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/bg_white_color"
        android:layout_gravity="center_vertical"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="10dp"
            android:gravity="center_vertical"
            android:text="满"
            android:textColor="@color/text_black_color"
            android:textSize="16sp" />

        <EditText
            android:id="@+id/ed_high"
            android:layout_width="50dp"
            android:layout_height="28dp"
            android:layout_centerVertical="true"
            android:background="@drawable/edit_bg_white"
            android:gravity="center"
            android:hint=""
            android:textColor="@color/text_dark_color"
            android:textColorHint="@color/text_hint_color"
            android:textSize="14sp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:gravity="center_vertical"
            android:text="可使用"
            android:textColor="@color/text_black_color"
            android:textSize="16sp" />

        <EditText
            android:id="@+id/ed_low"
            android:layout_width="50dp"
            android:layout_height="28dp"
            android:layout_centerVertical="true"
            android:background="@drawable/edit_bg_white"
            android:gravity="center"
            android:hint=""
            android:textColor="@color/text_dark_color"
            android:textColorHint="@color/text_hint_color"
            android:textSize="14sp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:gravity="center_vertical"
            android:text="以下红包"
            android:textColor="@color/text_black_color"
            android:textSize="16sp" />

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="right|center_vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_marginRight="10dp"
                android:gravity="center_vertical"
                android:text="|"
                android:textSize="16sp" />

            <ImageView
                android:id="@+id/iv_del_item"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_gravity="right"
                android:paddingRight="16dp"
                android:src="@drawable/icon_del"

                />
        </LinearLayout>

    </LinearLayout>
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="0.5dp"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginLeft="16dp"
        android:background="@color/text_hint_color" />

</LinearLayout>



2.把这个view插入到布局中,并放入到一个集合中,方便最后上传时使用

//1创建集合管理红包条件
	HashMap<Integer,LinearLayout> conditions = new HashMap<>();
	int itemId  =0;
	//红包使用条件的默认加入位置
	private int position = 7;
	private void createConditon() {
		//每次创建一个view
		LinearLayout ll_limit = (LinearLayout) View.inflate(this, R.layout.item_condition_edit_redbag, null);
		//删除按钮
		ImageView iv_del_item = (ImageView) ll_limit.findViewById(R.id.iv_del_item);
		//给每个删除条目绑定一个id
		iv_del_item.setTag(itemId);
		iv_del_item.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				//获取绑定的id
				int itemId = (int) v.getTag();
				//布局中删除指定位置的view
				ll_content_edit_redab2.removeView(conditions.get(itemId));
				//集合中删除指定的item对象
				conditions.remove(itemId);
				//记录position最新位置
				position--;
			}
		});
		//把当前对象保存到集合中
		conditions.put(itemId,ll_limit);
		ll_content_edit_redab2.addView(ll_limit, position);
		//每次添加以后,位置会变动
		position++;
		//每调用一次id++,防止重复
		itemId++;
	}
代码注释已经很详细了,简单提下:我用position记录view在布局中的位置,用itemid记录绑定的view


3.上传的代码:

Set<Map.Entry<Integer, LinearLayout>> items = conditions.entrySet();
		//转换为迭代器
		Iterator iter = items.iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			LinearLayout val = (LinearLayout) entry.getValue();
			EditText ed_high = (EditText) val.findViewById(R.id.ed_high);
			EditText ed_low = (EditText) val.findViewById(R.id.ed_low);
			String s1 = ed_high.getText().toString().trim();
			String s2 = ed_low.getText().toString().trim();
			if (TextUtils.isEmpty(s1) &&TextUtils.isEmpty(s2)){
				Toast.makeText(this,"限制条件填写不完整",Toast.LENGTH_SHORT).show();
				return;
			}
			limits.add(new RedbagLimit(s1,s2));
		}
		final String s = new Gson().toJson(limits);
		LogUtil.d("limit",s);
<pre style="font-family: 宋体; font-size: 10.5pt; background-color: rgb(255, 255, 255);"><pre name="code" class="java">List<RedbagLimit> limits = new ArrayList<>();
class RedbagLimit{
   String price ;
   String useable;
   RedbagLimit(String price ,String useable){
      this.price = price;
      this.useable = useable;
   }
}




因为上传的时候需要封装成一个数组,所以我先遍历获取数据再封装到集合中,通过gson转换成字符串。

第一次发文,有不对的地方请指正!

#include <stddef.h> #ifndef FASTERSTEREOCUDA_STEREO_H_ #define FASTERSTEREOCUDA_STEREO_H_ #ifndef FASTERSTEREOCUDA_EXPORTS #define FASTERSTEREOCUDA_DLL __declspec(dllimport) #else #define FASTERSTEREOCUDA_DLL __declspec(dllexport) #endif /** * \brief faster stereo algorithm based on cuda * Besides cuda, other optimization strategies are used, such as hierarchical optimization */ // class __declspec(dllexport) FasterStereoCuda class FasterStereoCuda { public: /**\brief parameters of polar image pairs*/ typedef struct EpipolarStereoParam{ double x0_left, y0_left; // image coordinates of principal point(left view) double x0_right, y0_right; // image coordinates of principal point(right view) double baseline; // baseline(mm) double focus; // focal length in pixel units EpipolarStereoParam(){ x0_left = y0_left = x0_right = y0_right = focus = baseline = 0; } }epi_ste_t; /**\brief parameters of stereo algorithm (for generating disparity map)*/ typedef struct StereoOption1 { int width; // width of image int height; // height of image int min_disp; // minimum disparity int max_disp; // maximum disparity int num_layers; // matching layers(the more layers the faster) bool do_lr_check; // whether to doing consistency check bool do_rm_peaks; // whether to removing peaks bool do_smooth; // whether to smoothing disparity map StereoOption1() : width(0), height(0), min_disp(0), max_disp(0), num_layers(1), do_lr_check(true),do_rm_peaks(true), do_smooth(false) {}; }ste_opt1_t; /**\brief parameters of stereo algorithm (for generating depth map)*/ typedef struct StereoOption2 { int width; // width of image int height; // height of image float min_depth; // minimum disparity float max_depth; // maximum disparity int num_layers; // matching layers(the more layers the faster) bool do_lr_check; // whether to doing consistency check bool do_rm_peaks; // whether to removing peaks bool do_smooth; // whether to smoothing disparity map epi_ste_t epi; // parameters of polar image pairs StereoOption2(): width(0), height(0), min_depth(0), max_depth(0), num_layers(1), do_lr_check(true), do_rm_peaks(true), do_smooth(false){} ; }ste_opt2_t; public: FasterStereoCuda(); ~FasterStereoCuda(); /** * \brief alloc page-locked memory on the host * by this way, you can get memory on the host with faster transmission speed between host(CPU) and device(GPU) * \param ptr device pointer to allocated memory * \param size requested allocation size in bytes * \return true: succeed false: filed */ static bool MallocPageLockedPtr(void** ptr, size_t size); /** * \brief frees page-locked memory * \param ptr pointer to memory to free * \return true: succeed false: filed */ static bool FreePageLockedPtr(void* ptr); public: /** * \brief initialization 1, for generating disparity map * \param option in, parameters of algorithm * \return true: succeed false: filed */ bool Init(const ste_opt1_t& option) const; /** * \brief initialization 2, for generating depth map * \param option in, parameters of algorithm * \return true: succeed false: filed */ bool Init2(const ste_opt2_t& option) const; /**\brief release*/ void Release() const; /** * \brief interface 1 : doing stereo matching to generate disparity map * \param bytes_left in��image data of left view * \param bytes_right in��image data of right view * \param disparity_data out��disparity map, the same size as image��you mast malloc memory in advance. invalid value : -999999.0f * \return true: succeed false: filed */ bool Match(const unsigned char* bytes_left, const unsigned char* bytes_right, float* disparity_data) const; /** * \brief interface 2 : doing stereo matching to generate depth map * \param bytes_left in��image data of left view * \param bytes_right in��image data of right view * \param depth_data out��depth map, the same size as image��you mast malloc memory in advance. invalid value : -999999.0f * \return true: succeed false: filed */ bool Match2(const unsigned char* bytes_left, const unsigned char* bytes_right, float* depth_data) const; private: void* impl_; }; 注释上述代码
最新发布
09-23
这段代码定义了一个名为`FasterStereoCuda`的类,用于实现基于CUDA的快速立体视觉算法。以下是代码的详细注释: ```cpp // 防止头文件重复包含 #ifndef FASTERSTEREOCUDA_STEREO_H_ #define FASTERSTEREOCUDA_STEREO_H_ // 导入标准库头文件 #include <stddef.h> // 定义DLL导入导出宏 #ifndef FASTERSTEREOCUDA_EXPORTS #define FASTERSTEREOCUDA_DLL __declspec(dllimport) #else #define FASTERSTEREOCUDA_DLL __declspec(dllexport) #endif /** * \brief 基于CUDA的快速立体视觉算法 * 除了CUDA外,还使用了其他优化策略,如分层优化 */ class FasterStereoCuda { public: /**\brief 极线图像对的参数*/ typedef struct EpipolarStereoParam{ double x0_left, y0_left; // 左视图主点坐标 double x0_right, y0_right; // 右视图主点坐标 double baseline; // 基线长度(mm) double focus; // 焦距(像素单位) EpipolarStereoParam(){ x0_left = y0_left = x0_right = y0_right = focus = baseline = 0; } }epi_ste_t; /**\brief 立体视觉算法参数(用于生成视差图)*/ typedef struct StereoOption1 { int width; // 图像宽度 int height; // 图像高度 int min_disp; // 最小视差 int max_disp; // 最大视差 int num_layers; // 匹配层数(层数越多越快) bool do_lr_check; // 是否进行一致性检查 bool do_rm_peaks; // 是否去除峰值 bool do_smooth; // 是否平滑视差图 StereoOption1() : width(0), height(0), min_disp(0), max_disp(0), num_layers(1), do_lr_check(true),do_rm_peaks(true), do_smooth(false) {}; }ste_opt1_t; /**\brief 立体视觉算法参数(用于生成深度图)*/ typedef struct StereoOption2 { int width; // 图像宽度 int height; // 图像高度 float min_depth; // 最小深度 float max_depth; // 最大深度 int num_layers; // 匹配层数(层数越多越快) bool do_lr_check; // 是否进行一致性检查 bool do_rm_peaks; // 是否去除峰值 bool do_smooth; // 是否平滑深度图 epi_ste_t epi; // 极线图像对参数 StereoOption2(): width(0), height(0), min_depth(0), max_depth(0), num_layers(1), do_lr_check(true), do_rm_peaks(true), do_smooth(false){} ; }ste_opt2_t; public: FasterStereoCuda(); // 构造函数 ~FasterStereoCuda(); // 析构函数 /** * \brief 在主机上分配页锁定内存 * 这种方式可以获得主机上传输速度更快的内存(CPU和GPU之间) * \param ptr 指向分配内存的设备指针 * \param size 请求分配的字节大小 * \return true: 成功 false: 失败 */ static bool MallocPageLockedPtr(void** ptr, size_t size); /** * \brief 释放页锁定内存 * \param ptr 要释放的内存指针 * \return true: 成功 false: 失败 */ static bool FreePageLockedPtr(void* ptr); public: /** * \brief 初始化1,用于生成视差图 * \param option 输入,算法参数 * \return true: 成功 false: 失败 */ bool Init(const ste_opt1_t& option) const; /** * \brief 初始化2,用于生成深度图 * \param option 输入,算法参数 * \return true: 成功 false: 失败 */ bool Init2(const ste_opt2_t& option) const; /**\brief 释放资源*/ void Release() const; /** * \brief 接口1:进行立体匹配生成视差图 * \param bytes_left 输入,左视图图像数据 * \param bytes_right 输入,右视图图像数据 * \param disparity_data 输出,视差图(与图像大小相同),需预先分配内存。无效值: -999999.0f * \return true: 成功 false: 失败 */ bool Match(const unsigned char* bytes_left, const unsigned char* bytes_right, float* disparity_data) const; /** * \brief 接口2:进行立体匹配生成深度图 * \param bytes_left 输入,左视图图像数据 * \param bytes_right 输入,右视图图像数据 * \param depth_data 输出,深度图(与图像大小相同),需预先分配内存。无效值: -999999.0f * \return true: 成功 false: 失败 */ bool Match2(const unsigned char* bytes_left, const unsigned char* bytes_right, float* depth_data) const; private: void* impl_; // 实现类的指针(隐藏实现细节) }; ```
评论 5
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值