Home > Net >  using single xml layout for multiple activity with different data
using single xml layout for multiple activity with different data

Time:08-10

I want to use single layout for multiple activities included in one activity but with different data. The problem is if I change text of one activity all other activities will have that text but I want that text in only that activity . is there any solution to use single layout in multiple activities included in one activity? any help would be appreciated.

CodePudding user response:

Hello you could use <include layout"@layout/...."/> to reuse your Layout

Android Developer Doc

CodePudding user response:

Solution 1 :

i think there is a solution from my perspective,

  1. create a class and extend the parent layout of your main XML file

  2. inflate your XML layout in your new custom class

  3. findViewByid or bindView to your dynamic attribute and make associate them with custom attributes to your custom view (Defining custom attrs)

  4. you will call your custom view and associate the new properties for each activity

Solution 2 :

Make a function in on create method of your activity after you will findviewbyid function for each your dynamic attribute and associate the desired value

CodePudding user response:

If i am not getting you wrong,

The problem is if I change text of one activity all other activities will have that text but I want that text in only that activity.

What you have to do is after setting content view in on create of each activity, then you should start changing the codes.

Sorry i don't know kotlin, am using java

Activity1.java

@Override 
public void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    setContentView(R.layout.general_activity);
    TextView activity1Text = findViewById(R.id.text);
    activity1Text.setText("activity 1");

One thing you should know is that the text has been changed to activity 1. So you need to change it in onCreate of each class that's extending AppCompatActivity or Activity since you're talking about activity.

Then in onDestroy() method of each activity, do something like this

@Override
public void onDestroy() {
    super.onDestroy();
    activity1Text.setText("");
}

Activity2.java

@Override 
public void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    setContentView(R.layout.general_activity);
    TextView activity2Text = findViewById(R.id.text);
    activity2Text.setText("activity 2");

Note: This should be done in onCreate method because that's where your activity is getting created.

Please upvote if it helps...

  • Related