我的按钮和视图在膨胀它们所在的布局后什么都不做,因此避免空对象错误

My buttons and Views do nothing after inflating the layout they are in so avoid null object error

我的主要 Activity。这是我所有代码的位置。

package com.abhiandroid.tablayoutexample;


import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.VideoView;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;

public class MainActivity extends AppCompatActivity {

    FrameLayout simpleFrameLayout;
    TabLayout tabLayout;
    ImageButton imageRopo;
    Button btn_show;
    InterstitialAd interstitialAd;
    AdView adView1,adView2;
    TextView textView;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LayoutInflater layoutInflater= (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View firstfrag =getLayoutInflater().inflate(R.layout.fragment_first,null);
        View thirdfrag =getLayoutInflater().inflate(R.layout.fragment_third,null);




        btn_show = (Button)thirdfrag.findViewById(R.id.bt_show);
        adView1= (AdView)thirdfrag.findViewById(R.id.ad_view);
        adView2= (AdView)thirdfrag.findViewById(R.id.ad_view2);
        imageRopo = (ImageButton)firstfrag.findViewById(R.id.buttonropo);
        textView  = (TextView)firstfrag.findViewById(R.id.testview);



        imageRopo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
                intent.setData(Uri.parse("https://www.youtube.com"));
                startActivity(intent);

                textView.setText("The button works");

            }
        });


        MobileAds.initialize(this, "ca-app-pub-8708219564656739~8048449285");

        AdRequest adRequest = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
                .addTestDevice("355696115338836").build();
        adView1.loadAd(adRequest);
        adView2.loadAd(adRequest);


        interstitialAd = new InterstitialAd(this);
        interstitialAd.setAdUnitId("ca-app-pub-8708219564656739/2401085524");
        interstitialAd.loadAd(new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
                .addTestDevice("355697115338836").build());


        btn_show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                interstitialAd.show();
            }
        });

        // get the reference of FrameLayout and TabLayout
        simpleFrameLayout = (FrameLayout) findViewById(R.id.simpleFrameLayout);
        tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout);
        // Create a new Tab named "First"
        TabLayout.Tab firstTab = tabLayout.newTab();
        firstTab.setText("Apps"); // set the Text for the first Tab
        firstTab.setIcon(R.drawable.app); // set an icon for the
        // first tab
        tabLayout.addTab(firstTab); // add  the tab at in the TabLayout
        // Create a new Tab named "Second"
        TabLayout.Tab secondTab = tabLayout.newTab();
        secondTab.setText("Products"); // set the Text for the second Tab
        secondTab.setIcon(R.drawable.company); // set an icon for the second tab
        tabLayout.addTab(secondTab); // add  the tab  in the TabLayout
        // Create a new Tab named "Third"
        TabLayout.Tab thirdTab = tabLayout.newTab();
        thirdTab.setText("Donate"); // set the Text for the first Tab
        thirdTab.setIcon(R.drawable.donation); // set an icon for the first tab
        tabLayout.addTab(thirdTab); // add  the tab at in the TabLayout


        // perform setOnTabSelectedListener event on TabLayout
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                // get the current selected tab's position and replace the fragment accordingly
                Fragment fragment = null;
                switch (tab.getPosition()) {
                    case 0:
                        fragment = new FirstFragment();
                        break;
                    case 1:
                        fragment = new SecondFragment();
                        break;
                    case 2:
                        fragment = new ThirdFragment();
                        break;
                }
                FragmentManager fm = getSupportFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                ft.replace(R.id.simpleFrameLayout, fragment);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                ft.commit();
            }



            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }
}

我的activit_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:clickable="true"
    android:focusable="true"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <android.support.design.widget.TabLayout
        android:id="@+id/simpleTabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabBackground="@android:color/darker_gray"
        app:tabIndicatorColor="#f00"
        app:tabSelectedTextColor="#f00"
        app:tabTextColor="#000" />

    <FrameLayout
        android:id="@+id/simpleFrameLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#9C27B0">

    </FrameLayout>

</LinearLayout>

按钮和视图位于不同的片段中,因此我不得不扩充它们所在的布局。

这是我的firstfragment.xml。这是我的按钮之一和我的 TextView 之一所在的位置。

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffeadb"
    tools:context=".FirstFragment">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#f7c5a8"
        android:orientation="vertical"
        tools:context=".FirstFragment"
        tools:layout_editor_absoluteY="1dp">

        <TextView
            android:id="@+id/textView23"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="4dp"
            android:fontFamily="@font/roboto_bold"
            android:gravity="center"
            android:text="Why Choose China when you have the option for Indian?"
            android:textSize="37sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="106dp"
            android:layout_height="109dp"
            android:layout_marginStart="24dp"
            android:layout_marginLeft="24dp"
            android:layout_marginTop="208dp"
            android:layout_marginEnd="281dp"
            android:layout_marginRight="281dp"
            android:src="@drawable/tiktokl"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/textView22"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="12dp"
            android:layout_marginLeft="12dp"
            android:layout_marginTop="148dp"
            android:layout_marginEnd="35dp"
            android:layout_marginRight="35dp"
            android:gravity="center"
            android:text="Why Choose Chinese when you can choose an Indian Alternative."
            android:textSize="16sp"
            android:textStyle="bold"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.255"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="114dp"
            android:layout_height="114dp"
            android:layout_marginStart="149dp"
            android:layout_marginLeft="149dp"
            android:layout_marginTop="192dp"
            android:layout_marginEnd="148dp"
            android:layout_marginRight="148dp"
            android:src="@drawable/red_arrow"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <ImageButton
            android:id="@+id/buttonropo"
            android:layout_width="132dp"
            android:layout_height="118dp"
            android:layout_marginStart="281dp"
            android:layout_marginLeft="281dp"
            android:layout_marginTop="183dp"
            android:layout_marginEnd="24dp"
            android:layout_marginRight="24dp"
            android:layout_marginBottom="5dp"
            android:adjustViewBounds="true"
            android:background="@android:color/transparent"
            android:baselineAlignBottom="false"
            android:cropToPadding="true"
            android:src="@drawable/roposoapplog"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/testview"
            android:layout_width="88dp"
            android:layout_height="19dp"
            android:layout_marginStart="168dp"
            android:layout_marginLeft="168dp"
            android:layout_marginTop="336dp"
            android:layout_marginEnd="155dp"
            android:layout_marginRight="155dp"
            android:textSize="25sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </android.support.constraint.ConstraintLayout>


</ScrollView>

我的 ThirdFragement Activity 文件非常空。

package com.abhiandroid.tablayoutexample;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;


public class FirstFragment extends Fragment {




 
    public FirstFragment() {
        // Required empty public constructor
    }
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


    }


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

在扩充布局之前,我会得到一个空对象错误,并且在扩充它们之后它们似乎不再有效。他们什么都不做。正如您在我的 MainActivity.java 文件中看到的那样,当用户单击一个按钮时,它会将他们重定向到一个网站。我什至制作了一个 TextView,它会在单击 Button 时自行更新,以便我知道 Button 正在工作。我花了几天时间试图修复这个错误,但没有取得任何进展。我怀疑这与制作片段时某些代码错误有关。

您应该在 Fragment class 中添加 Fragment 视图的逻辑。 因此,不要在 Activity 中执行按钮逻辑,而是在片段 onCreateView():

下执行
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_first, container, false);
    imageRopo = (ImageButton) v.findViewById(R.id.buttonropo);
    textView  = (TextView) v.findViewById(R.id.testview);

    imageRopo.setOnClickListener(new View.OnClickListener() { ...
    // ... and so on

    return v;
}