Reputation: 6509
I'm a little confused as to what I should be doing. I've read about fragments and I'm not sure if I should be using them here. I have 3 button in my main_layout file. What I'm doing incorrectly (I know) is that I have 3 different (but really similar) result xml files and 3 activity.java files. The result page is the same, just different text. There's no reason to have so many java files etc. I know there has to be a better way?
In my main_layout.xml, I have 3 ImageButtons:
In my MainActivity.java:
ImageButton ib1 = (ImageButton) findViewById(R.id.imageButton1);
ib1.setOnClickListener(this);
ImageButton ib2 = (ImageButton) findViewById(R.id.imageButton2);
ib2.setOnClickListener(this);
ImageButton ib3 = (ImageButton) findViewById(R.id.imageButton3);
ib3.setOnClickListener(this);
public void onClick(View v) {
if (v.getId() == R.id.imageButton1) {
startActivity(new Intent(Main.this, OneInfo.class));
} else if (v.getId() == R.id.imageButton2) {
startActivity(new Intent(Main.this, TwoInfo.class));
} else if (v.getId() == R.id.imageButton3) {
startActivity(new Intent(Main.this, ThreeInfo.class));
Upvotes: 2
Views: 360
Reputation: 234797
To cut down on the repetitive code, you can use a tag on the buttons:
int[] btnIds = { R.id.imageButton1, R.id.imageButton2, R.id.imageButton3 };
Class<?> classes = { OneInfo.class, TwoInfo.class, ThreeInfo.class };
for (int i = 0; i < btnIds.length; ++i) {
View btn = findViewById(btnIds[i]);
btn.setOnClickListener(this);
btn.setTag(classes[i]);
}
public void onClick(View v) {
Class<?> tag = (Class<?>) v.getTag();
if (tag != null) { // just in case
startActivity(new Intent(this, tag));
}
}
Upvotes: 2
Reputation: 93569
Map all 3 buttons to a single activity. Add an integer extra "mode" to it which specifies which of the 3 modes to use. In the activity, check the mode and set the text of the views that differ to the appropriate string using setText.
Upvotes: 2