这几天,开始一个项目,需要一个小效果,就是一个输入邮箱地址的EditTest 需要动态的添加。默认有两个,然后最多5个,手机的屏幕总是有限的
好的 ,这就上代码了
布局文件
这里时用一个有ID 的 LinearLayout 后面拿到它,向它加入EditTest 就OK了。
java 代码
package com.quseit.listedit.listedit;import android.support.v7.app.ActionBarActivity;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.EditText;import android.widget.LinearLayout;import android.widget.Toast;public class MainActivity extends ActionBarActivity { private LinearLayout layout_ll; private int edit_i=0; private String[] Param; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } public void initView(){ layout_ll=(LinearLayout)findViewById(R.id.layout_ll); } public void setEdit(){ EditText edit_l=new EditText(this); edit_i++; edit_l.setTag(edit_i); edit_l.setHint(edit_i + ""); edit_l.setText(edit_i + "zheshi"); layout_ll.addView(edit_l); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void onInsert(View v){ setEdit(); } public void onLast(View v){ int i=layout_ll.getChildCount(); EditText e =(EditText)layout_ll.getChildAt(i-1); Toast.makeText(this,e.getText().toString()+":"+i,Toast.LENGTH_SHORT).show(); } public void onFast(View v){ int i=layout_ll.getChildCount(); EditText e =(EditText)layout_ll.getChildAt(i-2); Toast.makeText(this,e.getText().toString()+":"+i,Toast.LENGTH_SHORT).show(); } public void getEditstr(){ int edit_i=layout_ll.getChildCount(); if(edit_i>0) { for (int i = 0; i < edit_i; i++) { EditText edit = (EditText) layout_ll.getChildAt(i); } } }}
其实,实现还是很简单的,只需要 getChildAt() 一下 拿到 LinearLayout里面的 节点 注意LinearLayout最好只放EditTest