我想在我的应用程序上动态创建两个字段TextView
和一个EditField
。现在,它通过setOnClickListener
通过一个按钮成功发生。当按下按钮时,TextView和EditField会在另一个的底部创建。部分代码如下:
MainActivity.java
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private GridLayout mlayout;
Button additem;
DynamicViews dnv;
Context context;
int f=0;
int counter = 2;
View view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mlayout = (GridLayout) findViewById(R.id.mylayout);
additem = (Button) findViewById(R.id.addButton);
additem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addView(view);
counter+=2;
}
});
}
public void addView (View view)
{
this.view=view;
f=f+1;
dnv = new DynamicViews(context);
mlayout.addView(dnv.descriptopionTextView(getApplicationContext(),Integer.toString(f)),counter);
mlayout.addView(dnv.receivedQuantityEditText(getApplicationContext()),counter+1);
}
DynamicViews.java
public class DynamicViews {
Context ctx;
public DynamicViews(Context ctx) {
this.ctx = ctx;
}
public TextView descriptopionTextView(Context context,String text) {
final ViewGroup.LayoutParams lParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(context);
textView.setLayoutParams(lParams);
textView.setTextSize(16);
textView.setTypeface(null, Typeface.BOLD);
textView.setTextColor(Color.rgb(255,255,255));
textView.setText(" "+ text+". ");
return textView;
}
public EditText receivedQuantityEditText(Context context) {
final ViewGroup.LayoutParams lParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
final EditText editText = new EditText(context);
int id = 0;
editText.setId(id);
editText.setTextSize(16);
editText.setTextColor(Color.rgb(255,255,255));
editText.setInputType(TYPE_CLASS_NUMBER);
return editText;
}
}
每次用户在动态创建的最后一个TextView
上按下Enter键时,如何创建新的两个字段EditField
和EditField
,并且该字段不为空?