在 android studio 中以编程方式删除按钮单击上的布局

2023-12-31

我在单击按钮时添加布​​局。

 private void addLayout() {
    layout2 = LayoutInflater.from(mContext).inflate(R.layout.product_layout, mLinearLayout, false);
    productAuto = (AutoCompleteTextView) layout2.findViewById(R.id.tv_product);
    qtyEditText = (EditText) layout2.findViewById(R.id.prod_qty);
    prodPriceEditText = (EditText)layout2.findViewById(R.id.prod_price);
    prodSpecsEditText = (EditText)layout2.findViewById(R.id.prod_specs);
    removeProduct = (Button)layout2.findViewById(R.id.btn_rmv);
    mLinearLayout.addView(layout2);
    setProd();
    this.initListenersPrd(getActivity());
}
private void initListenersPrd(final Context context) {
    productAuto.setOnItemClickListener((parent, view, position, id) -> {
        String newName = parent.getItemAtPosition(position).toString();
        ProductDetail productDetail = mProductManager.getProductByPrdName(newName);
        if (productDetail != null) {
           this.prodPriceEditText.setText(productDetail.getPrice());
           this.prodSpecsEditText.setText(productDetail.getProductSpec());
        }
    });

    removeProduct.setOnClickListener(v -> {
       if (mLinearLayout.getChildCount()>0)
       {
           ((LinearLayout)mLinearLayout.getParent()).removeView(mLinearLayout);
       }

    });}

现在我想从应用程序中删除特定的产品表单,所以我已经完成了((LinearLayout)mLinearLayout.getParent()).removeView(mLinearLayout);单击删除按钮。但它删除了动态添加的整个布局。

GUI

正如您在上图中看到的,我添加了 4-5 个产品布局,但是当我单击“删除”按钮时,我删除了所有布局。

Update 1

我在主布局中添加了以下布局,然后以编程方式调用其中的产品布局

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/ll_prod"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical" >

        </LinearLayout>

产品布局是单独创建的,我在主布局中调用它。

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2014 The Android Open Source Project

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 -->
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:orientation="vertical">
<LinearLayout
    android:id="@+id/ll_out"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/background_round"
    android:orientation="vertical"
    android:padding="5sp">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="10sp"
        android:orientation="horizontal">

        <AutoCompleteTextView
            android:id="@+id/tv_product"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="left|center_vertical"
            android:gravity="left"
            android:hint="Enter Product"
            android:inputType="text" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10sp"
        android:orientation="horizontal">
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight=".5"
            android:orientation="vertical">

            <EditText
                android:id="@+id/prod_qty"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:editable="false"
                android:focusable="true"
                android:focusableInTouchMode="true"
                android:hint="Enter Quantity"
                android:gravity="left"
                android:inputType="number" />
        </LinearLayout>
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight=".5"
            android:orientation="vertical">
            <EditText
                android:id="@+id/prod_price"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:editable="false"
                android:focusable="false"
                android:focusableInTouchMode="false"
                android:hint="Prod Price"
                android:gravity="left"
                android:inputType="none" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight=".5"
            android:orientation="vertical">

            <EditText
                android:id="@+id/prod_specs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:editable="false"
                android:focusable="false"
                android:focusableInTouchMode="false"
                android:gravity="left"
                android:hint="Prod Specs"
                android:inputType="none" />

        </LinearLayout>


    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="1dp"
        android:layout_marginTop="1dp"
        android:padding="0dp">

        <Button
            android:id="@+id/btn_rmv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Remove Product"
            android:textColor="@color/white" />
    </LinearLayout>
</LinearLayout>

每当我点击时就会调用上面的布局Add New Product Button.

如何删除特定布局?

任何帮助将不胜感激。


在这些情况下,将 RecyclerView 与 Adapter 结合使用是您的最佳选择。我的工作代码如下

类 列表适配器

package com.akshita.recycler;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class listAdapter extends RecyclerView.Adapter<listAdapter.ViewHolder> {
    private ArrayList<String> product_name;
    private ArrayList<Integer> quantity;
    private ArrayList<Double> price;
    private ArrayList<String> specs;
    private static Context scontext;

    public listAdapter(Context context)
    {
        scontext = context;
        this.product_name = new ArrayList<String>();
        this.price = new ArrayList<Double>();
        this.quantity = new ArrayList<Integer>();
        this.specs = new ArrayList<String>();
    }

    public listAdapter(Context context, ArrayList<String> pdname, ArrayList<Integer> quantity, ArrayList<Double> price, ArrayList<String> specs)
    {
        this.product_name = pdname;
        this.price = price;
        this.quantity = quantity;
        this.specs = specs;
        scontext = context;
    }

    @NonNull
    @Override
    public listAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater =  LayoutInflater.from(parent.getContext());
        View listItem = layoutInflater.inflate(R.layout.productview,parent,false);
        ViewHolder viewHolder = new ViewHolder(listItem);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull listAdapter.ViewHolder holder, int position) {
        holder.actv.setText(product_name.get(position));
        holder.qty.setText(quantity.get(position).toString());
        holder.price.setText(price.get(position).toString());
        holder.desc.setText(specs.get(position));

    }
    public void addView(String pdname, Double prc, Integer quant, String spec ) {

        product_name.add(pdname);
        quantity.add(quant);
        price.add(prc);
        specs.add(spec);
        notifyItemInserted(product_name.size());
        notifyItemInserted(quantity.size());
        notifyItemInserted(price.size());
        notifyItemInserted(specs.size());
    }

    public void removeAt(int position) {

        product_name.remove(position);
        quantity.remove(position);
        price.remove(position);
        specs.remove(position);
        notifyItemRemoved(position);
        notifyItemRangeChanged(position, product_name.size());
        notifyItemRangeChanged(position, quantity.size());
        notifyItemRangeChanged(position, price.size());
        notifyItemRangeChanged(position, specs.size());
    }

    @Override
    public int getItemCount() {
        return product_name.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
        public AutoCompleteTextView actv;
        public EditText qty;
        public EditText price;
        public EditText desc;
        public Button button;
        public ViewHolder(View itemView) {
            super(itemView);
            this.actv = itemView.findViewById(R.id.tv_product);
            this.qty = itemView.findViewById(R.id.prod_qty);
            this.price = itemView.findViewById(R.id.prod_price);
            this.desc = itemView.findViewById(R.id.prod_specs);
            this.button = itemView.findViewById(R.id.btn_rmv);
            button.setOnClickListener(this);
        }


        @Override
        public void onClick(View v) {
            if(v.equals(button)){
                removeAt(getAdapterPosition());
        }

        }
    }
}

我的主课

MainActivity.java

package com.akshita.recycler;

import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    listAdapter adapter;
    RecyclerView hs;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        hs = findViewById(R.id.rcview);

        hs.setHasFixedSize(false);
        hs.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
    }

    @Override
    public void onClick(View v) {
        switch(v.getId())
        {
            case R.id.add: addView(v);
        }
    }

    public void addView(View v)
    {
        if(adapter == null) {
            adapter = new listAdapter(this);
            hs.setAdapter(adapter);
        }
        adapter.addView("Name",0.0, 0, "Specs");
    }
}

产品视图.xml

<?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="wrap_content"
    android:orientation="vertical">
    <LinearLayout
        android:id="@+id/ll_out"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="5sp">


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="10sp"
            android:orientation="horizontal">

            <AutoCompleteTextView
                android:id="@+id/tv_product"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="left|center_vertical"
                android:gravity="left"
                android:hint="Enter Product"
                android:inputType="text" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10sp"
            android:orientation="horizontal">
            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight=".5"
                android:orientation="vertical">

                <EditText
                    android:id="@+id/prod_qty"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:editable="false"
                    android:focusable="true"
                    android:focusableInTouchMode="true"
                    android:hint="Enter Quantity"
                    android:gravity="left"
                    android:inputType="number" />
            </LinearLayout>
            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight=".5"
                android:orientation="vertical">
                <EditText
                    android:id="@+id/prod_price"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:editable="false"
                    android:focusable="false"
                    android:focusableInTouchMode="false"
                    android:hint="Prod Price"
                    android:gravity="left"
                    android:inputType="none" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight=".5"
                android:orientation="vertical">

                <EditText
                    android:id="@+id/prod_specs"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:editable="false"
                    android:focusable="false"
                    android:focusableInTouchMode="false"
                    android:gravity="left"
                    android:hint="Prod Specs"
                    android:inputType="none" />

            </LinearLayout>


        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="1dp"
            android:layout_marginTop="1dp"
            android:padding="0dp">

            <Button
                android:id="@+id/btn_rmv"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Remove Product"
                android:textColor="@color/white" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

活动主文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:gravity="center|top"
    android:orientation="vertical">
    <Button
        android:id="@+id/add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="addView"
        />
    <androidx.recyclerview.widget.RecyclerView
        android:layout_marginTop="10dp"
        android:id="@+id/rcview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
    />
</LinearLayout>

完整的工作代码可用在 GitHub 上 https://github.com/VanshajDaga/Recycler

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 android studio 中以编程方式删除按钮单击上的布局 的相关文章

随机推荐

  • 尝试解码数据(将 Abs 导出到 MySQL)

    我有数据库表 DROP TABLE translation en lt CREATE TABLE translation en lt id INTEGER lt translation WIDEMEMO BLOBBlockSize 1024
  • 如何使用 Log4j 和 Storm Framework 将日志写入文件?

    我在 Storm 中使用 log4j 记录到文件时遇到了一些问题 在提交我的拓扑之前 即在我的主要方法中 我编写了一些日志语句并使用以下方法配置了记录器 PropertyConfigurator configure myLog4jPrope
  • 组装键盘IO口

    我看过以下内容topic https stackoverflow com questions 219120 x86 assembly protected mode keyboard access 我有兴趣通过 IN OUT 指令联系键盘并设
  • Spring Web Flow - 如何使用对话范围中已有的值设置单元测试?

    我正在开发一个使用 Spring Web Flow 2 0 的项目 我正在尝试对从决策状态开始的流程进行单元测试 决策状态检查位于conversationScope 我不知道如何将值插入到conversationScope用于单元测试 我努
  • 根据系统动态判断整数类型(c++)

    我正在编写一个程序 以每 32 位 即一次 4 个字节 为单位将数据存储到文件中 我在64位Windows系统中编写代码 但我使用的编译器是32位 mingw32 在当前系统中 int和long的大小是相同的 都是32位 4字节 我目前正在
  • 使用 AWK 将多个文件中的列添加到 csv 表

    我希望通过使用 AWK 从多个文件中获取值来构建 csv 表 我让它处理两个文件 但我无法扩展它 我目前正在获取第二个文件的输出 并附加第三个文件 依此类推 以下是示例文件 file1 file2 file3 file4 100 45 1
  • 无法安装包收缩[关闭]

    Closed 这个问题需要调试细节 help minimal reproducible example 目前不接受答案 我跑了 pip install contractions in jupyter notebook并且无法安装库收缩并显示
  • 模式同义词签名:必需与提供的约束

    我想我明白了 不寻常形式 的约束 https downloads haskell org 7Eghc 8 10 5 docs html users guide glasgow exts html typing of pattern syno
  • Reactjs - 输入默认值已设置但未显示

    注意到一些奇怪的现象 即为输入设置了 defaultValue 但有时刷新页面时它不可见 我尝试过 console log 然后组件在加载数据时重新渲染多次 在最后一次重新渲染时 组件包含所需的值 如屏幕截图所示 但未显示 知道为什么吗 谢
  • 关闭 GDB 中设置断点的确认[重复]

    这个问题在这里已经有答案了 在共享库上设置断点 gdb b file c 278 No symbol table is loaded Use the file command Make breakpoint pending on futur
  • 文本编辑器告诉光标位置的索引

    我需要一个文本编辑器来告诉我光标的位置 这样我就可以确定要加载到字符串中的文本范围 不幸的是 我尝试过的文本编辑器 TextWrangler Aquamacs EditPad 只告诉我光标所在的行号以及该行上的字符索引 我需要从文件开头到该
  • 如何聚合来自异步生产者的数据并将其写入文件?

    我正在学习 C 中的异步 等待模式 目前我正在尝试解决这样的问题 有一个生产者 硬件设备 每秒生成 1000 个数据包 我需要将这些数据记录到文件中 该设备只有一个ReadAsync 一次报告单个数据包的方法 我需要缓冲数据包并按照它们生成
  • 将用户身份验证详细信息存储在单独的表中的优点

    我在 mysql 中有一个用户表 其中包含所有用户数据 名字 姓氏 地址等 但是我是否应该将身份验证详细信息存储在另一个表 用户名 密码 中并通过用户 ID 链接这两个表 这其中有什么道理吗 是不是更安全 或者它只是添加额外的编码 这其中有
  • 将 Typescript 2.3 模块发布到 NPM 以供 Angular 4 使用

    里面有相关说明在 Typescript 中编写 NPM 模块 https stackoverflow com questions 30928253 writing npm modules in typescript 但是它已经过时了 现在有
  • 在 Swift 中创建像这样的普通框窗口吗?

    下面是 App Store 上 Squish 应用程序的屏幕截图 我怎样才能制作一个这样的窗口 带有圆角并且标题栏和内容之间没有分隔符 唯一的区别是我想在标题栏上有一个标题 简而言之 如何制作一个如图所示但带有标题的窗口 在Xcode中创建
  • 在 BS 3 中对齐标签和文本框

    我正在尝试使用 Bootstrap 3 对齐标签和文本框 这不起作用 因为 开始日期 被包装了 我也尝试过 form horizo ntal 但对我没有帮助 div class row div class col xs 3 input gr
  • 为什么我的 Swift 包获取了错误的主体类?

    我做了一个捆绑目标 它的Info plist文件指定一个非常具体的类 我们称之为PrincipalClass 应该是它的主要类 这个类是用 Swift 编写的 并且具有 objc属性 这Info plist文件已正确复制到捆绑包中 并且我已
  • 是否存在使用代数数据类型或多态性的 OOP 抽象类的 Haskell 等效项?

    在Haskell中 是否可以编写一个带有签名的函数 该函数可以接受两种不同 尽管相似 的数据类型 并根据传入的类型进行不同的操作 一个例子可能会让我的问题更清楚 如果我有一个名为myFunction 以及两种名为MyTypeA and My
  • 如何使用 Expect 为 Perl 脚本输入密码?

    我希望在运行安装脚本时自动输入密码 我在 Perl 中使用反引号调用了安装脚本 现在我的问题是如何使用输入密码expect或者是其他东西 my op install sh f my conf p my ip s my server 执行上述
  • 在 android studio 中以编程方式删除按钮单击上的布局

    我在单击按钮时添加布 局 private void addLayout layout2 LayoutInflater from mContext inflate R layout product layout mLinearLayout f