如何在片段中创建按钮?

How to create a button in fragment?

主页片段代码:

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);
        
    }

}

我想在此片段中创建一个按钮,以便在我按下该按钮时显示广告。

由于您是从片段中扩充布局 fragment_home,因此您需要在该 xml 布局文件中添加按钮。

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>

请注意,我们在上面添加了值为 my_button 的属性 android:id。现在这有助于我们在片段 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
            }
        });