2012-12-09 111 views
3

我有一個包含EditText和2個按鈕的XML佈局。如果我點擊加號按鈕,編程添加一個新的編輯文本。這有效,但edittext看起來不同。根據XML,在XML中定義的edittext沒有任何特殊屬性,所以我相信它不是一個特定的佈局設置。以編程方式添加的EditText不同於XML版本

我的問題是如何讓我的程序化添加EditText的外觀一樣?

包含數字的EditText包含我編程添加的edittext。空的是在XML中創建的。

screenshot http://www.tozz.nl/temp/screenshot.png

代碼:

 LinearLayout baseLayout = (LinearLayout) findViewById(R.id.baseLayout); 

     LinearLayout linearLayout = new LinearLayout(getApplicationContext()); 
     linearLayout.setId(100 + numPlayers); 
     linearLayout.setOrientation(LinearLayout.HORIZONTAL); 

     EditText editText = new EditText(getApplicationContext()); 
     editText.setText(editText.toString().substring(25, 30)); 

     ImageButton delButton = new ImageButton(getApplicationContext()); 
     delButton.setImageResource(R.drawable.ic_delete); 

     linearLayout.addView(editText); 
     linearLayout.addView(delButton); 

     baseLayout.addView(linearLayout); 

我的XML是如下:

<LinearLayout 
     android:id="@+id/linearPlayer1" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:orientation="horizontal" > 

     <EditText 
      android:id="@+id/editPlayer1" 
      android:layout_width="0dip" 
      android:layout_height="wrap_content" 
      android:layout_gravity="center" 
      android:layout_weight="1" 
      android:gravity="center_vertical" /> 



     <ImageButton 
      android:id="@+id/addPlayer1" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:src="@drawable/ic_input_add" /> 

    </LinearLayout> 
+2

發佈代碼,並添加那些額外的'EditTexts'。 – Luksprog

+0

其簡單:\t \t \t EditText editText = new EditText(getApplicationContext()); editText.setText(editText.toString()。substring(25,30)); –

+0

並將它們添加到哪種佈局中以及如何添加? – Luksprog

回答

3

添加那些意見跟正確的LayoutParams應使EditText像最初一個從佈局:

linearLayout.addView(editText, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 
      LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f)); 
    linearLayout.addView(delButton, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 
      LinearLayout.LayoutParams.WRAP_CONTENT)); 

    baseLayout.addView(linearLayout, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, 
      LinearLayout.LayoutParams.WRAP_CONTENT)); 
+0

謝謝,但這不是我的意思。在你的代碼中,佈局(寬度,右邊的按鈕等)是固定的。但是EditText仍然有不同的風格。請參閱新的截圖。我的意思是說,XML編輯文本只是一個整齊的輸入,而我添加的編輯文本是灰色的框。 ![新的截圖](http://www.tozz.nl/temp/screenshot2.png) –

+0

@ user1750795你可以發佈'EditText'的xml佈局代碼嗎?添加的'EditTexts'外觀有一個禁用的'EditText'框('setEnabled(false)'在代碼中的某處?)。你在你的應用中使用了一些庫嗎? – Luksprog

+0

當然,請參閱編輯後。 –

5

Luksprog回答我的問題:

創建新的看法時傳遞活動上下文,而不是應用程序上下文。