How to use the same UI with multiple java files? ANDROID JAVA

78 views Asked by At

I'm a newbie and I'm working on a Unit Converter.

I would like to open the same UI regardless of which button I click(Weight or Length) main_activity.xml UI

activity_main.xml

Below is the UI I want to open: activity_conversion.xml UI

activity_conversion.xml

And I would like each button in the main_activity to run on a different java class. So, (minus the main_activity.java and it's .xml file) I have 1 xml file(activity_conversion.xml) and 2 java files one for each button of the main_activity.xml

activity_main.xml Weight button

android:onClick="weightPage"

activity_main.xml Length button

android:onClick="lengthPage"

MainActivity.java

public void weightPage(View view){
    Intent intent = new Intent(this, WeightActivity.class);
    startActivity(intent);
}

public void lengthPage(View view) {
    Intent intent2 = new Intent(this, LengthActivity.class);
    startActivity(intent2);
}

Length_Activity.java code for Length button

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_conversion);
}

setContentView() method doesn't work for me:( Thanks in advance!

1

There are 1 answers

0
Shreemaan Abhishek On

I would like to open the same UI regardless of which button I click(Weight or Length)

You can do that by creating an activity and its layout XML file. And then start that activity via explicit intent like this:

//Place this code inside the onClick method
Intent intent = new Intent(SoucreActivity.this, DestinationActivity.class);
startActivity(intent); 

And I would like each button in the main_activity to run on a different java class.

No, you cannot. All UI elements on a screen are always in the same activity; they cannot run on different java classes. (Unless you are using fragments of which you need not worry about as you are a newbie)

Apparently, you want the two buttons in your main activity to open the same activity. Which you can achieve using intents using the code snippet mentioned above.