[英]I want to create a checkbox when button is clicked
我想讓它每次有人在editText
中輸入editText
並單擊按鈕時,文本就會出現。 它在我的代碼中完成,但我還想在它旁邊添加一個復選框。 每次按下按鈕時如何添加復選框?
這是我在 editText 中鍵入 test 后,它現在在模擬器中的樣子:
https://gyazo.com/6b9a050976ecd2c4b509220263bbdce1
第二個問題是:當我寫第二個 todo 時,它會覆蓋最后一個,所以現在我只能有 1 個 todo。 為什么?
代碼:
final TextView textViewPrint;
Button btn_print;
final EditText editTextType;
textViewPrint = findViewById(R.id.print_text);
btn_print = findViewById(R.id.button_add);
editTextType = findViewById(R.id.test_textEdit);
btn_print.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
textViewPrint.setText(editTextType.getText().toString()) ;
editTextType.setText("");
}
});
您可以在布局膨脹后以編程方式將其添加到布局中。 給你的 LinearLayout 添加一個 id:
android:id ="@+id/layout"
然后在 OnCreate 中(在您現有的代碼之后),獲取對它的引用並根據需要添加控件。 並在 OnCreate 中添加這些行,例如:
LinearLayout l = (LinearLayout)findViewById(R.id.layout);
CheckBox cb = new CheckBox(this);
int lHeight = LinearLayout.LayoutParams.MATCH_PARENT;
int lWidth = LinearLayout.LayoutParams.WRAP_CONTENT;
l.addView(cb, new LinearLayout.LayoutParams(lHeight, lWidth));
setContentView(l);
LinearLayout l = (LinearLayout)findViewById(R.id.layout);
btn_print.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CheckBox cb = new CheckBox(this);
LayoutParams lparams = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
cb.setLayoutParams(lparams);
l.addView(cb);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.