-1

I have my main activity. Inside this main activity I want to create an unknown number of layouts that each one of them include one button. I want smart way to do it - make the layout one time and than use it a lot of time.

enter image description here

What is a good way to do it? Thanks

  • I think it is. but what do I do about the unknown number of layouts i need. Is there a way to do it programlly? – ohad avraham Feb 14 '22 at 23:03
  • When asking questions on StackOverflow please do some research before asking: https://stackoverflow.com/search?q=%5Bandroid%5D+add+a+layout+programmatically Also what you ask is covered by the various free online Android courses. This site works best with specific programming question where you show what you've tried. – Morrison Chang Feb 14 '22 at 23:26
  • You can **not** create a view **one** time and use it **multiple times**. Android does not like it, and will you an exception. I have tried. – Darkman Feb 15 '22 at 05:36
  • Thank you very much – ohad avraham Feb 15 '22 at 21:58

2 Answers2

1

Make One Layout Resource File Using Below Code

 <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    
        <androidx.appcompat.widget.AppCompatTextView
            android:layout_width="match_parent"
            android:layout_height="@dimen/_100sdp"
            android:layout_marginTop="@dimen/_15sdp"
            android:gravity="center"
            android:textColor="@color/black"
            android:textSize="@dimen/_13sdp" />
    
        <Button
            android:layout_width="match_parent"
            android:layout_height="@dimen/_35sdp"
            android:layout_marginStart="@dimen/_5sdp"
            android:layout_marginTop="@dimen/_20sdp"
            android:layout_weight="1"
            android:gravity="center"
            android:text="Submit"
            android:textColor="@color/white"
            android:textSize="@dimen/_10sdp" />
    
    </LinearLayout>

And In Your Main Activity Layout You Can Use Only

  <include layout="@layout/layoutresourcefilename"/>
Mit Patel
  • 59
  • 6
1

Trying to be smart commonly results in the opposite. Better keep it simple;
Which means, just add three buttons and then show either one of them.
This has the advance, that the events are already bound, ready to click.
And also, meanwhile it's a whole lot more common to inflate Fragment
or to data-bind views, which would permit for hiding/showing buttons.

Martin Zeitler
  • 1
  • 19
  • 155
  • 216