Entire react native app showing on lockscreen Entire react native app showing on lockscreen

How to Add buttons programmatically to a fragment

If you’ve encountered challenges in adding image buttons to a fragment within a ViewPager in Android, you’re not alone. The provided code snippet and solution address a common issue where buttons fail to appear despite no apparent errors in the code.

The problem lies in the fact that the images are being created programmatically, but they are not being added to the main layout. Let’s dissect the solution provided:

public class ViewPagerFragment extends Fragment {
  // ... (existing code)

  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment, container, false);

  public void onActivityCreated(Bundle savedInstanceState) {
    FrameLayout fl =
        (FrameLayout) this.getActivity.findViewById(R.id.frameLayout1);
    int[] image_array = {

    for (int i = 0; i < image_array.length; i++) {
      ImageButton b1 = new ImageButton(getActivity());
      b1.setId(100 + i);

      RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
      if (i > 0) {
        lp.addRule(RelativeLayout.BELOW, b1.getId() - 1);

      ImageHolder ih = new ImageHolder(getActivity());

  public class ImageHolder extends FrameLayout {
    // ... (existing code)

Understanding the Solution

The crucial part of the solution lies in the onActivityCreated method. Here, after inflating the fragment, images are dynamically created, and an ImageHolder is used to contain each ImageButton. Importantly, these image holders are then added to the main layout using fl.addView(ih).

This step is essential for ensuring that the programmatically created images become part of the fragment’s layout and are displayed correctly.


Adding buttons programmatically to a fragment in Android, especially within a ViewPager, requires careful handling of the layout. The provided solution addresses the common issue of buttons not appearing despite the absence of errors. By dynamically creating image buttons and ensuring they are added to the main layout, developers can overcome this challenge and enhance the user interface of their Android applications.