我想用一个 Buttonclick 创建一些 EditText 字段,它们有自己的名称(eText1,eText2 ...)例如有一个按钮 +。用户可以单击该按钮来创建一个新的 EditText 字段。
问问题
5878 次
1 回答
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);
}
编辑2:完整代码:
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()
我很着急。
于 2013-01-21T16:00:53.847 回答