<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/parentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/buttonView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Create Edit Text" >
</Button>
</LinearLayout>
MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.InputType;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
public class MainActivity extends Activity {
private Button buttonView;
private LinearLayout parentLayout;
private int hint=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonView=(Button)findViewById(R.id.buttonView);
parentLayout = (LinearLayout)findViewById(R.id.parentLayout);
buttonView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
createEditTextView();
}
});
}
protected void createEditTextView() {
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams (
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.setMargins(0,10,0,10);
EditText edittTxt = new EditText(this);
int maxLength = 5;
hint++;
edittTxt.setHint("editText"+hint);
edittTxt.setLayoutParams(params);
// edtTxt.setBackgroundColor(Color.WHITE);
edittTxt.setInputType(InputType.TYPE_CLASS_TEXT);
edittTxt.setTextSize(TypedValue.COMPLEX_UNIT_SP,18);
edittTxt.setId(hint);
InputFilter[] fArray = new InputFilter[1];
fArray[0] = new InputFilter.LengthFilter(maxLength);
edittTxt.setFilters(fArray);
parentLayout.addView(edittTxt);
}
}
只需创建一个新的 EditText(View) 并将其添加到您的 layout 中,放置在首选位置即可。
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.linearLayoutDecisions);
EditText editText = new EditText(this);
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
editText.setLayoutParams(p);
linearLayout.addView(editText);
ListView
或RecyclerView
,因为视图数量未定义,如果数量增加会导致内存问题。 - M.Waqas Pervez