我想通过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)