【发布时间】:2014-06-07 06:59:58
【问题描述】:
我正在以编程方式创建一个RelativeLayout,我想将三个对象放入其中:一个ListView 和两个Buttons。我需要设置一些设置才能在窗口中正确定位它们。现在我正在这样做:
RekativeLayout rl = new RelativeLayout(context);
rl.setBackgroundColor(Color.WHITE);
rl.setPadding(10, 10, 10, 10);
ListView listView = new ListView(context);
ListViewAdapter adapter = new ListViewAdapter(jParser.getArrayList(), context);
listView.setLayoutParams(new LayoutParams(wWidth, wHeight));
listView.setAdapter(adapter);
RelativeLayout.LayoutParams listParams = new RelativeLayout.LayoutParams(wWidth, wHeight);
listParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
listParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
listView.setId(98515);
listView.setLayoutParams(listParams);
Button moreButton = new Button(context);
moreButton.setLayoutParams(lp);
moreButton.setBackgroundColor(Color.GRAY);
moreButton.setText("More");
RelativeLayout.LayoutParams mButtonParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
mButtonParams.addRule(RelativeLayout.ALIGN_LEFT, listView.getId());
mButtonParams.addRule(RelativeLayout.BELOW, listView.getId());
mButtonParams.setMargins(0, 10, 0, 0);
moreButton.setLayoutParams(mButtonParams);
closeButton.setLayoutParams(lp);
closeButton.setBackgroundColor(Color.GRAY);
closeButton.setText("Close");
Button closeButton = new Button(context);
RelativeLayout.LayoutParams cButtonParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
cButtonParams.addRule(RelativeLayout.ALIGN_RIGHT, listView.getId());
cButtonParams.addRule(RelativeLayout.BELOW, listView.getId());
cButtonParams.setMargins(0, 10, 0, 0);
closeButton.setLayoutParams(cButtonParams);
rl.addView(listView);
rl.addView(moreButton);
rl.addView(closeButton);
但我猜这种方法需要很多系统资源并且是不可接受的。我应该如何正确设置设置?
【问题讨论】:
-
but I guess this method requires much system resources and isn't acceptable. How should I set the settings properly?你能辩解吗? -
这就是布局资源存在的原因。
-
@nKn 我的论点是为每个视图创建新的
RelativeLayout对象可能会消耗系统的大量内存。但是根据您的回答,我现在认为我错了!那么这是以编程方式管理布局的正确方法吗? -
我的回答是,实际上这主要取决于您的布局。您有 2 种方法来定义
View,作为布局资源和动态(这就是您正在做的事情)。如果你的意思是这样做,这是正确的方法。 “更多行”并不意味着更复杂/效率低下,我认为这将更多地取决于您在RelativeLayout(重ImageViews 等)中放置的内容。毕竟,您设置的属性与定义布局文件一样,只是方式不同。 -
感谢您提供非常全面的答案!
标签: java android layout view params