Why do you have to create a new set of RelativeLayout.LayoutParams for each element you put in your view?
I have to do this programmatically. So, bear with me.
I have text and two buttons that I set to align below each other. So I created a new Relative开发者_JS百科Layout.LayoutParams instance for each and added a rule to set it below one another. That works and I'm happy with it.
My question is: why do I have to create a new instance in order for the layout to display them this way? Is there any way to reduce the following code so that it's not so repetitive (besides writing my own private method to dry it up. I'm wondering whether there's a way to accomplish the same thing in fewer lines of code utilizing something I've possibly overlooked in the Android SDK)? Do I have to keep creating a new RelativeLayout.LayoutParams instance for each element?
layout = new RelativeLayout(this);
layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
text = new TextView(this);
text.setId(1);
text.setText("This is text");
layout.addView(text);
myButton1 = new Button(this);
myButton1.setId(2)
myButton1.setOnClickListener(this);
RelativeLayout.LayoutParams buttonParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
buttonParams.addRule(RelativeLayout.BELOW, text.getId());
layout.addView(myButton1, buttonParams);
myButton2 = new Button(this);
myButton2.setId(3)
myButton2.setOnClickListener(this);
buttonParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
buttonParams.addRule(RelativeLayout.BELOW, myButton1.getId());
layout.addView(myButton2, buttonParams);
Unfortunately, there is no removeRule()
method for RelativeLayout.LayoutParams
(at least according to the API) so you have to create a new LayoutParams
object each time.
I would tend to agree with @jeffamaphone that you should prefer xml layouts over programmatically setting the layout. Even if you don't put the entire layout in an xml, you should use the resource id (see doc for details) to set the id's for the items. This will guarantee a unique id.
you can set whatever rule you added to false using 0.
buttonParams.addRule(RelativeLayout.BELOW, 0);
精彩评论