2013-07-30 25 views
-1

我想在java中定義3個彼此相鄰的edittext。無法在java中正確定義edittexts

protected void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.activity_main); 

    // LinearLayout 
    mainLayout=(LinearLayout)findViewById(R.id.linearLayout); 

    // LinearLayout -> RelativeLayout 
    main=new RelativeLayout(this); 
    mainParams=new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
    main.setLayoutParams(mainParams); 
    mainLayout.addView(main); 

    // LinearLayout -> RelativeLayout -> EditText1 
    EditText item1=new EditText(this); 
    item1.setHint("Enter the item"); 
    item1.setId(5); 
    RelativeLayout.LayoutParams etParams=new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
    etParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT); 
    item1.setLayoutParams(etParams); 
    main.addView(item1); 

    // LinearLayout -> RelativeLayout -> EditText2 
    EditText quantity1=new EditText(this); 
    item1.setHint("Quantity"); 
    item1.setId(6); 
    RelativeLayout.LayoutParams qparams=new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
    etParams.addRule(RelativeLayout.ALIGN_LEFT, 5); 
    item1.setLayoutParams(qparams); 
    main.addView(quantity1); 

    // LinearLayout -> RelativeLayout -> EditText3 
    EditText rate1=new EditText(this); 
    item1.setHint("rate"); 
    item1.setId(7); 
    RelativeLayout.LayoutParams rparams=new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
    etParams.addRule(RelativeLayout.ALIGN_RIGHT, 6); 
    item1.setLayoutParams(rparams); 
    main.addView(rate1); 

`

我知道你可能會想,我也能做到這一點的XML,但事情是,我有在運行時創造更多edittexts。

問題是,所有的editText都互相重疊。 PLZ幫助

+2

這是因爲您將它們添加到RelativeLayout。如果您希望它們呈現在另一個之下,請使用LinearLayout。如果你在運行時定義了很多視圖,你應該考慮將它們放在一些適配器視圖中,也就是ListView –

回答

0

原因可能是因爲您創建了quantity1rate1,但在創建實例後仍保留配置item1實例。修復代碼配置quantity1rate1

+0

對於這個錯誤感到抱歉。但它們仍然重疊 – kayveesin

0
  1. 我不知道你有多少EditTexts需要,但如果它是一個相對較小的金額,你可以顯示/隱藏他們爲你在Java中的願望。

    您可以使用此方法來顯示或隱藏TextView

    yourTextViewName.setVisibility(View.GONE); //makes XML element disappear 
    yourTextViewName.setVisibility(View.VISIBLE); //makes XML element appear 
    

    所以在你的代碼,而不是創建新EditText,則可以顯示現有的,你已經設置了位置。

  2. 你應該考慮使用LinearLayout,因爲這可能會阻止你的TextViews被創建在彼此之上。