我想通過2個Textviews之間的代碼動態地創建一個相對的佈局。如何通過Android中的代碼實現android:layout_below屬性。 任何人都可以幫助我解決這個問題。如何在Android中使用RelativeLayout動態創建UserInterface
由於事先
我想通過2個Textviews之間的代碼動態地創建一個相對的佈局。如何通過Android中的代碼實現android:layout_below屬性。 任何人都可以幫助我解決這個問題。如何在Android中使用RelativeLayout動態創建UserInterface
由於事先
final TextView upperTxt = (...)
upperTxt.setId(12345);
final TextView lowerTxt = (...);
final RelativeLayout.LayoutParams params = RelativeLayout.LayoutParams(this, null);
params.addRule(RelativeLayout.BELOW, 12345);
lowerTxt.setLayoutParams(params);
這是我對我的特殊問題的解決方案。
如果在數據庫中找不到用戶名,我不得不創建一個類似於xml生成的RelativeLayout。
// text view appears on top of the edit text
enterNameRequest = new TextView(mainActivity.getApplicationContext());
// fill the view with a string from strings.xml
enterNameRequest.setText(mainActivity.getResources().getString(R.string.enterNameRequest));
// edit text appears below text view and above button
enterName = new EditText(mainActivity.getApplicationContext());
enterName.setId(667);
// button appears at the bottom of the relative layout
saveUserName = new Button(mainActivity.getApplicationContext());
saveUserName.setText(mainActivity.getResources().getString(R.string.useUserName));
saveUserName.setId(666);
// generate the relative layout
RelativeLayout layout = new RelativeLayout(mainActivity.getApplicationContext());
layout.setId(668);
// set a background graphic by its id
layout.setBackgroundDrawable(mainActivity.getApplicationContext().getResources().getDrawable(R.drawable.background_head_neutral));
// runtime told me that i MUST use width and height parameters!
LayoutParams params2 = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
params2.addRule(RelativeLayout.ABOVE, 666);
enterName.setLayoutParams(params2);
LayoutParams params3 = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
params3.addRule(RelativeLayout.ABOVE, 667);
enterNameRequest.setLayoutParams(params3);
LayoutParams params4 = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
params4.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 668);
saveUserName.setLayoutParams(params4);
// add views
layout.addView(enterNameRequest);
layout.addView(enterName);
layout.addView(saveUserName);
/* todo: set button action */
mainActivity.setContentView(layout);
我發現了什麼額外的: 它也不是那麼好從Java中手動操作的佈局!
您應該更好地使用新的活動並在其中設置新的佈局。
這樣,應用程序代碼的可讀性就好多了!
我甚至試圖在一個活動中設置幾個佈局(不是手動的,但機智setContentView)在一個活動,事實證明,我不知道在哪裏訪問什麼其他...此外,我有一個很大的問題加入onClickListeners ......讓你更好的使用 - 安卓的onClick =「myButtonMethod」 - 在你的XML標記按鈕,在你根據活動,其採用的佈局,像這樣有一個方法:
public void myButtonMethod(View v){
// do stuff
}
這可以提高性能,因爲您沒有使用額外的偵聽器 - 但是您可以使用已經可用的偵聽器,而且它在每種情況下都與您的活動綁定。
ü可以嘗試這
LinearLayout.LayoutParams leftMarginParams =新LinearLayout.LayoutParams( LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);`` leftMarginParams.leftMargin = 50;
Button btn1 = new Button(this);
btn1.setText("Button1");
linLayout.addView(btn1, leftMarginParams)