Check this:
public class YourActivity extends Activity {
private LinearLayout holder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity);
holder = (LinearLayout) findViewById(R.id.holder);
addNewEdit();
}
private void addNewEdit() {
final EditText newEdit = (EditText) getLayoutInflater().inflate(R.layout.new_edit, holder, false);
holder.addView(newEdit);
newEdit.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() == 0 && holder.getChildCount() > 1) {
holder.removeView(newEdit);
} else if (s.length() > 0 && ((before + start) == 0)) {
addNewEdit();
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
}
your_activity.xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/holder"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
And new_edit.xml:
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
</EditText>
EDIT: Of course, you should set the correct paddings / margin and perhaps create your own and stylized layouts for the holder and the items you are inflating.
source
share