我想用一个Buttonclick创建一些EditText字段,它们有自己的名字(eText1,eText2 ......) 例如,有一个按钮+。用户可以单击该按钮以创建新的EditText字段。
答案 0 :(得分:3)
您提供的内容很少,但这段代码可能会为您带来更多信息:
EditText et1, et2, et3;
public void onCreate() {
et1 = (EditText)findViewById(R.id.et1);
et2 = (EditText)findViewById(R.id.et2);
et3 = (EditText)findViewById(R.id.et3);
et1.setVisibility(View.GONE);
et2.setVisibility(View.GONE);
et3.setVisibility(View.GONE);
}
public void clickHandlingMethod(View v) {
et1.setVisibility(View.VISIBLE);
et2.setVisibility(View.VISIBLE);
et3.setVisibility(View.VISIBLE);
}
您只需隐藏所有EditTexts
,并在用户按下button
时将其显示为可见。
编辑:看到您的评论,用户最多可以添加100 EditTexts
,您可能想要制作更具动态性的内容。试试这个,在Button
点击上创建并添加一个:
ScrollView container; // create a scrollView in which you can put all EditTexts
static int totalEditTexts = 0;
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
container = (ScrollView) findViewById(R.id.scrollView);
}
public void clicked(View view) {
totalEditTexts++;
if (totalEditTexts > 100)
return;
EditText editText = new EditText(this);
//if you want to identify the created editTexts, set a tag, like below
editText.setTag("EditText" + totalEditTexts);
container.addView(editText);
}
Edit2:完整代码:
public class ScrollStuff extends Activity {
LinearLayout containerLayout;
static int totalEditTexts = 0;
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.scroll);
containerLayout = (LinearLayout)findViewById(R.id.mlayout);
}
public void onBackPressed() {
totalEditTexts++;
if (totalEditTexts > 100)
return;
EditText editText = new EditText(this);
containerLayout.addView(editText);
editText.setGravity(Gravity.RIGHT);
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) editText.getLayoutParams();
layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT;
editText.setLayoutParams(layoutParams);
//if you want to identify the created editTexts, set a tag, like below
editText.setTag("EditText" + totalEditTexts);
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="@+id/mlayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
请原谅我糟糕的命名选择以及我使用onBackPressed()
进行点击事件的事实,我非常着急。