0

I have a button. I want to write the function "onClick" for the button. Each time that I click on it I want a new button to be created on screen. And also that new button to be added into an array list of buttons.

I searched but I couldn't find any answer. All of the answers talk about creating buttons with drop and drag, not with dynamic creation of them.

Thanks

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click to add"
        android:id="@+id/B1"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:onClick="clicktoaddcode"
        />
</RelativeLayout>

package com.example.yas.dynamicbutton;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void clicktoaddcode(View V){
        Toast.makeText(MainActivity.this, "Created", Toast.LENGTH_SHORT).show();
    }
}
1
  • You're going to need to make your question a lot more clear and provide the code you have so far plus what is/isn't happening to receive a good answer. Commented Oct 18, 2015 at 4:05

3 Answers 3

2

You must using ArrayList.

List<Button> btnList = new ArrayList<>();

// Call Your ClickListener
btnList.add(new Button(YourContext));
YourParent.addView(btnList.get(btnList.size() - 1 ));

Edited

MainActivity.java

public class MainActivity extends AppCompatActivity {

    LinearLayout container;

    List<Button> btnList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        container = (LinearLayout)findViewById(R.id.container);


    }

    public void addBtn(View v){
        btnList.add(new Button(this));
        container.addView(btnList.get(btnList.size() - 1 ));
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:fitsSystemWindows="true"
    tools:context=".MainActivity">

    <LinearLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:clickable="true"
        android:onClick="addBtn">

    </LinearLayout>

</android.support.design.widget.CoordinatorLayout>
Sign up to request clarification or add additional context in comments.

9 Comments

in "YourContext" and "YourParent" what should I write?
instead of YourContext you must set your activity instance and YourParent is main layout that you want add Button inside it
would you please send me a small example? XML file and mainactivity.java thank you
Thanks. I did it but I have a question: TextView T = new TextView(MainActivity.this); T.setText(Hello); setContentView(T); the textview appear on the button that I hade. I want to have 81 textview 9*9 like.
where is your question?! it's just description
|
1

Have this for your XML -

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center">

        <Button
            android:id="@+id/myButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Add one more" />

        <LinearLayout
            android:orientation="vertical"
            android:id="@+id/myLinearLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center">

        </LinearLayout>

    </LinearLayout>
</ScrollView>

And this in Java-

final LinearLayout linearLayout = (LinearLayout)findViewById(R.id.myLinearLayout);
    Button button = (Button)findViewById(R.id.myButton);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Button button = new Button(MainActivity.this);
            button.setText("A new Button");
            linearLayout.addView(button);
        }
    });

3 Comments

When I run it: unfortuately Program name has stoped.
You should know to use the Log to find what's going wrong. This piece of code works just fine. There's gotta be some other issue with other parts of your code.
E/AndroidRuntime: java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.yas.dbutton/com.example.yas.dbutton.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
0

The most simple method to create an unlimited size array is using String Builder. This allows you to add many elements in runtime. It has 3 major components.

  1. Declaration and Initialization.
  2. Value addition/ Append
  3. Print out/ Usage

Use the bellow code anywhere in Android Studio.

//Basic Decleration
        StringBuilder myString = new StringBuilder();
        
//Adding data
       myString.append("Hello text <br>");
        myString.append("some more data <br>");
        myString.append("more data to store <br>");
        
//Displaying in already created text view
        deviceDetails.setText(Html.fromHtml(callLogs+""));

Note: I'm treating this as HTML string and " " tags will create the next line in text view. So, all added data will be displayed in a new line.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.