开发者

Dynamic views with one static xml

I have an xml file right now which has a TableLayout within a LinearLayout. Within the TableLayout are 开发者_开发问答TableRows with Buttons. Within my Java code, I do a setOnClickListener for each button.

The problem is I have several xml files like this which are exactly the same, except within the xml the ID and text's of the different buttons are different.

So one file it will be

<Button android:id="@+id/one" android:text="one" /> 
<Button android:id="@+id/two" android:text="two" /> 

and another file it will be

<Button android:id="@+id/three" android:text="three" />
<Button android:id="@+id/four" android:text="four" />

In Java, in one part of a switch/case statement I have a case that is:

setContentView(R.layout.a);
Button bOne = (Button) findViewById(R.id.one);
Button bTwo = (Button) findViewById(R.id.two);

and another I have:

setContentView(R.layout.b);
Button bThree = (Button) findViewById(R.id.three);
Button bFour = (Button) findViewById(R.id.four);

The redundancy goes out to more than two xml files, this is just an example.

Is there any way to do this and not have multiple layout files, but to do this all in one layout file? The xml files are all exactly the same, but for the id and text portions of the buttons.

I really don't care how this is done - in Java, in xml, or however. It's just that I make minor tweaks to the layout once in a while, and don't want to have to continue to tweaking every file with exactly the same layout but for the button id's and texts. I'd like to tweak the layout once and have it work across all of them when I change the layout. If I have to put the entire layout file in Java, that would be fine.


just keep one xml file (a.xml). say the ids of the two buttons be id1 and id2. use setContentView(R.layout.a);. Next declare 2 buttons say b1 and b2. set b1 = (Button) findViewById(R.id.id1) and b2 = (Button) findViewById(R.id.id2). put setOnClickListener for the buttons in the switch-case


If it is always just those 2 buttons, you could have a variable keeping track of an arbitrary int that represents what screen you're on. Keep the same buttons, change their text / layout params, and on the OnClick() method test that variable to see what screen you're on.


Why not just lose the xml files and just make it all dynamic. You can do everything in code that you can in xml. Here is a tutorial: Dynamic Layout Tutorials

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜