Issue
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.
Solution
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
}
});
Answered By - Rajasekhar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.