Dynamically create buttons

Asked

Viewed 1,315 times

5

I’m making a screen where register some users. On this screen, I have a ScrollView with a Gridlayout inside, with 2 columns. Each column has 1 button, which when clicking, opens a link, in this case, 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" />...

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, only now it’s starting to have a lot of buttons, and it’s getting kind of hard to keep creating button like this. Would there be a way to create buttons dynamically, retrieving the name and url of the database link or something? I was going to add the image here to see what the layout looks like, but it’s too big.

Edit The layout looks like this: http://imgur.com/uzEoq5l

inserir a descrição da imagem aqui

  • 3

    Using a Listview would not solve the problem?

  • put the photo on a photo hosting site

  • Edit: posted the image.

  • How to make buttons clickable in a listview?

  • You’ll have to make a custom listview. Basically, you will have an xml that will represent a single item in the list and you will also have an adapter class that will have to receive a list of Strings with the button names and will also be responsible for linking the data from this list of Strings in the buttons that appear on the screens. Wait for the code.

  • got it, do it with a listview of images currently, if you have how to do with buttons, great

  • 1

    Recycler View...

  • Images Voce uses Imageview in xml. Buttons just use Button in xml... It’s the same principle; only changes the widget’s appearance.

  • Easier than Listview I believe you are using Gridview. https://developer.android.com/guide/topics/ui/layout/gridview.html

  • What you want is to take various data (URL, name, etc.) and create the buttons automatically, correct? Yes, first you need to pull the data from somewhere (sqlite, remote database, webservice, json, etc.) and run a script for that. I’ve seen it once. I’ll see if I can find it and put it on. But to get ahead of it, there’s a way.

  • That’s a similar question I asked, and I haven’t tried it yet: Take programmatically generated Edittext values ... You can get an idea I believe.

Show 6 more comments

1 answer

0

Voce can create a layout for the buttons:
Filing cabinet btn_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<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"
</Button>

Create an Adapter for that button.
Filing cabinet GridButtonsAdapter.java:

public class GridButtonsAdapter extends BaseAdapter {
    private ArrayList<String> list;

    @Override 
    publc int getCount() {
        return list.size;
    }

    @Override 
    public String getItem(position: int) {
        return list[position];
    }

    @Override
    public long getItemId(position: int) {
        return (long)position;
    }

    private Context mContext;
    GridButtonsAdapter(Context context, ArrayList<String> btnsNames) {
        this.mContext = context;
        this.list = btnsNames;
    }

    @SuppressLint("ViewHolder")
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Inflate o view personalizado
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        Button itemLayout = (LinearLayout) inflater.inflate(R.layout.btn_layout, null);

        Button cellBtn = itemLayout.findViewById<View>(R.id.demondies);

        String name = list[position]

        cellBtn.setText(name)
        cellBtn.tag(name)
        return row
    }
}

then in its main Activity Voce mounts the Adapter

//...
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
    // criar o metodo para preencher a sua lista de urls para o itemclick
    ArrayList<String> urlList = pegaSuaListaDeUrlsDoSeuDatabase();
    // criar o metodo para preencher a sua lista de nomes do seu database
    // voce pode criar um metodo void e criar esses dois campos no escopo
    // da classe e preencher os dois campos num unico metodo void onde
    // voce pega os valores para os nomes e para as urls, assim, simplifica
    // e diminui o codigo
    ArrayList<String> btnsNamesList = pegaSuaListaDeNomesDoSeuDatabase();
    // monta o adapter para a sua GridView
    GridLayout gridbtns = findViewById(R.id.suagrid);
    GridButtonsAdapter mAdapter = new GridButtonsAdapter(this, btnsNamesList);
    // cria um listener para o onItemClick de cada button dentro do adapter
    AdapterView.OnItemClickListener listener = (arg0, arg1, position, id) -> {
        // aqui voce pega um determinado item da lista de urls
        Uri uri = Uri.parse(urlList.get(position));
        // e passa ela para o intent
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
    };
    // passa o listener paa o click do adapter
    gridbtns.setOnItemClickListener(listener);
    // passa o adapter para a grid
    gridbtns.setAdapter(mAdapter);
}

so Voce will be able to create your buttons dynamically.
Logically, this is just an example.
I hope it helps you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.