我正在研究一個應用程序,我必須動態創建多個 EditText
和Spinner。所以我開始尋找 的解決方案,因爲我沒有權限在XML文件中使用Invisible 屬性。我搜索了很多,只有stackoverflow得到了幾個例子 。我遵循他們並創建了這個程序。在Android中動態創建EditText
**MainActivity.java code**
public class MainActivity extends Activity {
RelativeLayout containerLayout;
static int totalEditTexts = 0;
Button button;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
containerLayout = (RelativeLayout)findViewById(R.id.relative1);
button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
totalEditTexts++;
if (totalEditTexts > 100)
return;
EditText editText = new EditText(getBaseContext());
containerLayout.addView(editText);
editText.setGravity(Gravity.RIGHT);
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) editText.getLayoutParams();
layoutParams.width = RelativeLayout.LayoutParams.MATCH_PARENT;
layoutParams.setMargins(23, 34, 0, 0);
// RelativeLayout.LayoutParams()
editText.setLayoutParams(layoutParams);
//if you want to identify the created editTexts, set a tag, like below
editText.setTag("EditText" + totalEditTexts);
}
});
}}
當我運行這段代碼,它創建的EditText得到了單擊按鈕時。但只有一次。之後我不知道發生了什麼。無論是創建新的EditText還是重疊舊的EditText,否則不會創建多個EditText。
誰能解釋我什麼,我現在要做的,以解決此問題。