0

Home fragment code:

public class HomeFragment extends Fragment {

    Button interstitial;
    Button BannerAd;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_home, container, false);
        
    }

}

I want to create an button in this fragment for showing ads when I press that button.

postgresnewbie
  • 1,378
  • 1
  • 12
  • 19
Buddy
  • 581
  • 2
  • 11

1 Answers1

1

Since you are inflating layout fragment_home from fragment, you need to add button inside that xml layout file.

fragment_home.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
    tools:context=".HomeFragment">

    <Button
        android:id="@+id/my_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Button" />

</FrameLayout>

Notice we have added attribute android:id with value my_button above. Now this helps us to get reference to it in fragment class.

HomeFragment.java

        // Inside your onViewCreated() add this code to get reference from layout.

        Button myButton = view.findViewById(R.id.my_button);
        myButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Add your code
            }
        });
Rajasekhar
  • 1,297
  • 2
  • 10
  • 19
  • hey brother check my new problem https://stackoverflow.com/questions/64767123/store-offline-firebase-database-android @Rajasekhar – Buddy Nov 10 '20 at 10:39
  • Hey brother please check my new question https://stackoverflow.com/questions/65024641/download-pdf-and-open-it-in-google-doc-with-download-notification @Rjasekhar – Buddy Nov 27 '20 at 10:21