在我的项目中,我在运行时生成了一些EDITTEXT,EDITTEXT的数量是可变的。 必须恢复键入的文本并存储在不同的变量中,然后用它创建一个JSON对象。
以下是我用来创建EditText的方法:
public View editText(String nmLabel, String tpRender) {
EditText e = new EditText(getBaseContext());
e.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
// e.setHint("DATE");
if(tpRender.equals("NUMBER")) {
e.setHint("NUMBER");
}
else if(tpRender.equals("DATE")) {
e.setHint("DATE");
}
else if(tpRender.equals("TEXT")) {
e.setHint("TEXT");
}
e.setTextColor(Color.BLACK);
e.setTextSize(20);
return(e);
}
如何单独输入文字?
答案 0 :(得分:0)
由于您的EditTexts是在运行时创建的,并且您需要从所有这些中获取值来创建您的json,您可以使用List并在那里存储您的各个EditTexts。类似的东西:
在xml文件中:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
android:id="@+id/layout">
</LinearLayout>
在您的活动中,
List<EditText> allEditTexts; // The List to hold all EditTexts
LinearLayout layout; // The anchor layout
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = (LinearLayout) findViewById(R.id.layout);
allEditTexts = new ArrayList<EditText>();
// I am running it three times, you can run as many times as you want
for (int i = 0; i < 3; i++) {
EditText editText = (EditText) editText("ANY LABEL", "NUMBER");
layout.addView(editText);
allEditTexts.add(editText);
}
// Now I am adding a button that will read the values from the List when clicked
Button button = new Button(getApplicationContext());
button.setText("Click");
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Read the input here for all EditTexts. Then you can store it in some Array or process it differently. In my code I have just logged them.
for (EditText editText : allEditTexts) {
Log.d("TEXTINPUT", editText.getText().toString());
}
}
});
layout.addView(button);
}
// This is the code that you have, almost untouched.
public View editText(String nmLabel, String tpRender) {
EditText e = new EditText(getBaseContext());
e.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
// e.setHint("DATE");
if (tpRender.equals("NUMBER")) {
e.setHint("NUMBER");
} else if (tpRender.equals("DATE")) {
e.setHint("DATE");
} else if (tpRender.equals("TEXT")) {
e.setHint("TEXT");
}
e.setTextColor(Color.BLACK);
e.setTextSize(20);
allEditTexts.add(e);
return (e);
}
希望这能帮到你!