skip to Main Content

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.

5

Answers


  1. Chosen as BEST ANSWER

    There is no way to do that. I wrote my functionalities again in the activity where I have included my layout


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

    Android Developer Doc

    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
  4. 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.

    Login or Signup to reply.
  5. for example, you can use multiple linear layouts, each with its own data, then you can set the visibility of each layout according to the activity.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search