【问题标题】:How to add a new checkbox when I click a button? [duplicate]单击按钮时如何添加新复选框? [复制]
【发布时间】:2018-09-13 21:41:09
【问题描述】:

checkbox should be created in red zone when button is clicked

我试过这个:

public void newcheckbox() {
  LinearLayout my_layout = (LinearLayout)findViewById(R.id.my_layout);

  CheckBox checkBox = new CheckBox(getApplicationContext());
  checkBox.setText(""+ETnewcheckbox.getText().toString());
  my_layout.addView(checkBox);
}

【问题讨论】:

  • 您的具体问题是什么
  • 试过了吗?干得好!
  • 点击该按钮时应用程序崩溃
  • 与问题和整个活动代码共享您的崩溃日志
  • 查看已编辑问题中的图片

标签: android button checkbox


【解决方案1】:

您应该使用Recycleview。 为您的复选框创建一个基本模型,例如

class CheckboxModel{
 private  String text;
 private  boolean value;
...
}

您应该使用 ViewHolder 创建您的 CheckboxAdapter 并在用户单击按钮时更新您的适配器。 adapter.setItems(list);(别忘了告诉那个 notifyDataSetChanged)

【讨论】:

  • 我是菜鸟。你能给我密码吗...
【解决方案2】:

在您的 XML 中:

 <LinearLayout
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:orientation="vertical"
     android:paddingBottom="8dp"
     android:paddingEnd="16dp"
     android:paddingStart="16dp"
     android:paddingTop="8dp">

           <Button
               android:id="@+id/btCalculator"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:text="click" />

           <CheckBox
               android:id="@+id/cbVar"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:visibility="gone" />

 </LinearLayout>

在您的 Java 类中: 在 OnCreate 之前:

Button btCalculator;
CheckBox cbVar;

在 OnCreate 中:

cbVar= findViewById(R.id.cbVar);

btCalculator = findViewById(R.id.btCalculator);

btCalculator.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            cbVar.setVisibility(View.VISIBLE);
        }

【讨论】:

  • 实际上我想添加用户想要的复选框。当用户在 EditText 中输入文本时,应将带有该文本的新复选框添加到视图中
猜你喜欢
  • 1970-01-01
  • 2014-02-25
  • 2012-07-22
  • 1970-01-01
  • 2011-07-19
  • 2012-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多