Android:按下按钮时以编程方式添加EditText
问题描述:
我正在处理SMS应用程序。我有一个“+”按钮,当用户单击该按钮时,新的ExitText将出现在现有的下方,供用户输入多个电话号码发送文本。任何人都可以请帮助创建一个新的EditText时按下按钮?Android:按下按钮时以编程方式添加EditText
谢谢你,
答
我会保持EditText
的List
一个对象,并添加一个新的
EditText toAdd = new EditText(this);
list.add(toAdd);
对按钮按下列表。另外,请阅读此链接以了解如何将新的EditText
添加到您当前的布局。 How to lay out Views in RelativeLayout programmatically?
当您知道用户已完成并想要保存号码时,请遍历List
的EditText
对象。
+0
谢谢你的帮助,我会尽力实现这一点。 – aa051
答
我构建了一个应用程序,它根据数据库中的行数来动态添加按钮。
基本上我发现它更容易创建长度等于按键的数字键的排列,我需要: 在你的情况......
final int PHONE_NUMBERS = 0;
final int OTHER_STUFF = 1;
final int MORE_STUFF = 2;
LinearLayout MyEditTextLayout;
EditText []DynamicFields = new EditText[3];
*note these should be declared outside of onCreate*
then within onCreate {
MyEditTextLayout = (LinearLayout) findViewById (R.id.Whatever_you_named_your_layout_in_xml);
}
then in your onClickListener dialog:
final EditText editText = new EditText();
if(button = myPhoneNumberButton)
{
editText.layout_width = "fill_parent";
editText.hint = "Enter Phone Numbers Here";
DynamicFields[PHONE_NUMBERS] = editText; //that way you can refer to your editTexts later
MyEditTextLayout.addView(editText);
}
请注意我在工作中快速输入了这一点所以代码可能无法正常工作,但这应该给你一个良好的开始评论,如果您有任何问题!
答
为了内部创建一个EditText一个对话框,您可以在按钮的OnClickListener做到这一点:
final FrameLayout fl = new FrameLayout(ContactView.this);
final EditText txtSms = new EditText(ContactView.this);
txtSms.setRawInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
txtSms.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
txtSms.setHorizontallyScrolling(false);
txtSms.setVerticalScrollBarEnabled(true);
txtSms.setGravity(Gravity.CENTER);
fl.addView(txtSms, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT));
final AlertDialog.Builder builder = new AlertDialog.Builder(ContactView.this);
//building the custom AlertDialog
builder.setView(fl).setTitle("Enviar mensaje").setCancelable(false)
.setPositiveButton("Send", new DialogInterface.OnClickListener(){
//What happens when the positive button is pressed
public void onClick(DialogInterface d, int which){
if(txtSms.getText().toString().length() != 0){
enviarSms(txtSms.getText().toString());
d.dismiss();
}else{
Toast.makeText(((Dialog) d).getContext(), "Can't send an empty message", Toast.LENGTH_SHORT).show();
}
}
//What happens when the negative button is pressed
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface d, int which) {
d.dismiss();
}
}).create().show();
显示您的布局,其中+ is.also要添加EditText.It按钮是所有关于在布局中添加视图 – Rasel
@rds:我很抱歉,但我是Android新手,刚开始使用它。我试图谷歌它,但无法找到它,并要求我在这里发布了一个问题。 – aa051