Reputation: 267
I am fairly new to Android development.
I want to create a screen that has a horizontal scroll view of buttons (group names). Every time I click a group name, it will display the members below these buttons (I assume I will have to create a fragment with a listView of members. I haven't gotten to the last part. I was able to create a horizontal scroll view in XML and add 6 button to the XML file. But what I want to do is use Java to find the number of groups every time onCreate is called, so it can create the appropriate number of buttons based on groups. (Group names are currently stored in a temporary ArrayList (for testing purposes) and I use arrayList.size() to get the number of buttons needed to be created. The difficulty I am having is figuring out how to create these buttons inside the LinearLayout inside the HorizontalScrollView inside the RelativeLayout. I messed around with creating one layout adding a button, but I don't know how to create nested layouts, or access the LinearLayout in which I want to create my buttons using Java. Here is my XML file (I created one button for testing. That button location is where I want to create my buttons using Java. I don't want to have anything written there in XML if possible. Everytime a new group is created, a button has to be created):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFBB00">
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/horizontalScrollView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="@+id/buttonList">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me 1"
android:id="@+id/button"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</LinearLayout>
</HorizontalScrollView>
</RelativeLayout>
How do I add buttons using my Java class in this LinearLayout?
Upvotes: 2
Views: 5364
Reputation: 368
Since you are talking about dynamic content, you might want to try something like a horizontial list view and create an adapter instead of creating a bunch of buttons at runtime. It will be a bit slower and more resource intensive to do it that way.
Here is an example using RecyclerView: How to build a Horizontal ListView with RecyclerView?
Upvotes: 1
Reputation: 1235
Use this link how to add button dynamically in android? and there is another way doing this by using loop, Read this article for making button using loops
Upvotes: 1