Add a dynamic button and specify a method when it’s getting clicked

I have a button and in XML it looks like this:

<Button
    android:id="@+id/hello"
    android:layout_width="match_parent"
    android:tag="Greeting"
    android:layout_height="60dp"
    android:gravity="center_vertical"
    android:onClick="onClick"
    android:text="@string/hello" />

Also, I have the method public void onClick(View view) {}. So whenever I click on that button, that method should run. Well, that works fine.

Now, I would like to add dynamic buttons.

if (_layout == R.layout.fragment_general) {
    LinearLayout layout = view.findViewById(R.id.root);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        for(String text : readFromSharedPreferences(getContext())) {
            Button btn = new Button(this.getContext());
            btn.setText(text);
            btn.setTag(text);
            btn.setTextColor(Color.BLUE);
            btn.setBackgroundColor(Color.RED);
            layout.addView(btn);
        }
    }
}

The buttons will be added but when I click on them, nothing happens.

I have also tried it with btn.performClick() and btn.callOnClick() but none of them works. In those methods I am missing a parameter. So it should be btn.performClick("onClick") or btn.callOnClick("onClick"). However, I should be able to tell that the method onClick should be executed when I click on a dynamic button. How can I do this?

Answer

try this code :-

if (_layout == R.layout.fragment_general) {
            LinearLayout layout = view.findViewById(R.id.root);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                for (String text : readFromSharedPreferences(getContext())) {
                    Button btn = new Button(this.getContext());
                    btn.setText(text);
                    btn.setTag(text);
                    btn.setTextColor(Color.BLUE);
                    btn.setBackgroundColor(Color.RED);
                    layout.addView(btn);

                    btn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Toast.makeText(MainActivity.this, "Clicked", Toast.LENGTH_SHORT).show();
                        }
                    });
        }
    }
}

you just simply have to add setOnClickListener after btn added to linear layout. it’s working for me