Create buttons dynamically

5

I'm doing a screen where I register some users. On this screen, I have a ScrollView with a Gridlayout inside, with 2 columns. Each column has 1 button, which when clicked, opens a link in the case of Youtube.

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true">

    <GridLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:columnCount="2"
        android:paddingLeft="10dp"
        android:paddingRight="10dp">

        <Button
            android:layout_width="0dp"
            android:layout_height="90dp"
            android:layout_columnWeight="1"
            android:gravity="center"
            android:layout_gravity="fill_horizontal"
            android:background="@drawable/bg_button"
            android:text="DemonDies"
            android:onClick="demondies"
            android:textColor="@color/textColorPrimary"
            android:id="@+id/demondies" />...

Then in JAVA I do the rest:

 Button demondies,...
 demondies = (Button) view.findViewById(R.id.demondies);

demondies.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            Uri uri = Uri.parse("https://www.youtube.com/channel/UCEWQoXe934RcJr04efPm9OQ");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }
    });...

So far blz, but now it's starting to have many buttons, and it's getting kind of hard to continue creating buttons like that. Would you have a way to dynamically create buttons by retrieving the name and url of the database link or something? I would add the image here to see how the layout is, but it gets very large.

Edit The layout looks like this: link

    
asked by anonymous 17.02.2017 / 14:53

1 answer

0

I think you'd better create a RecyclerView:

        <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:numColumns="2"/>

then in activity:

    final GridLayoutManager mGlm = new GridLayoutManager(this, 2);
    recyclerview.setLayoutManager(mGlm);
    recyclerview.setHasFixedSize(true);
    YourAdapter adapter= new YourAdapter(yourList);
    recyclerview.setAdapter(adapter);

Then just create your adapter and make the click event there!

    
04.04.2018 / 01:43