简体   繁体   中英

why setOnClickListener doesnt work in my view pager?

I have a view pager and cardview in my activity and define lottie animation for my favorite btn but the code of setOnClickListener didnt work and app did crash when i go to this activity

when i comment the setOnClickListener code, it will ok and also the code is working well in another activity

this is my java activity code

public class MainActivity3 extends AppCompatActivity {

    ImageView imageView;
    String[] money;
    boolean switchIsOn = false;

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

//favorite animation button 
        final LottieAnimationView animatedSwitchButton =(LottieAnimationView) findViewById(R.id.fav_lot);
        animatedSwitchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (switchIsOn){
                    animatedSwitchButton.setSpeed(-1);
                    animatedSwitchButton.playAnimation();
                    switchIsOn = false;
                }else {
                    animatedSwitchButton.setSpeed(1);
                    animatedSwitchButton.playAnimation();
                    switchIsOn = true;
                }
            }
        });


        money = getResources().getStringArray(R.array.money);
        ViewPager mViewPager = findViewById(R.id.viewPager);
        CardPagerAdapters mCardAdapter = new CardPagerAdapters();

        for (String s : money) {
            mCardAdapter.addCardItem(new CardItemString(s));
        }

        mViewPager.setAdapter(mCardAdapter);
        mViewPager.setOffscreenPageLimit(3);
    }
}

and the adapter.xml

<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView 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:id="@+id/cardView"
    android:layout_width="250dp"
    android:layout_height="320dp"
    app:cardCornerRadius="20dp"
    android:layout_gravity="center"
    android:backgroundTint="#00FFFFFF">


    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#6FCDDC39"
        android:padding="15dp">

        <TextView
            android:id="@+id/titleTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_alignParentEnd="true"
            android:layout_gravity="center_horizontal"
            android:fontFamily="sans-serif-black"
            android:gravity="center_horizontal"
            android:text="@string/app_name"
            android:textColor="#075AFF"
            android:textSize="24sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <com.airbnb.lottie.LottieAnimationView
            android:id="@+id/fav_lot"
            android:layout_width="100dp"
            android:layout_height="100dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.533"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/titleTextView"
            app:lottie_rawRes="@raw/fav" />


    </androidx.constraintlayout.widget.ConstraintLayout>
</com.google.android.material.card.MaterialCardView>

the logcat error is

2020-11-24 16:47:40.817 11330-11330/com.paradise.myapplication4 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.paradise.myapplication4, PID: 11330
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.paradise.myapplication4/com.paradise.myapplication4.MainActivity3}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.airbnb.lottie.LottieAnimationView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:440)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.airbnb.lottie.LottieAnimationView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at com.paradise.myapplication4.MainActivity3.onCreate(MainActivity3.java:26)
        at android.app.Activity.performCreate(Activity.java:7009)
        at android.app.Activity.performCreate(Activity.java:7000)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) 
        at android.app.ActivityThread.-wrap11(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6494) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:440) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 

mainActivity.xml

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

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false"
        android:overScrollMode="never"
        android:paddingVertical="100dp"
        android:paddingHorizontal="30dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"/>

</RelativeLayout>

cardIPagerAdapter java code

public class CardPagerAdapters extends PagerAdapter {

    private final List<CardView> mViews;
    private final List<CardItemString> mData;
    private float mBaseElevation;




    public CardPagerAdapters() {
        mData = new ArrayList<>();
        mViews = new ArrayList<>();
    }

    public void addCardItem(CardItemString item) {
        mViews.add(null);
        mData.add(item);
    }

    public int getCount() {
        return mData.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @NonNull
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View view = LayoutInflater.from(container.getContext())
                .inflate(R.layout.adapter, container, false);
        container.addView(view);
        bind(mData.get(position), view);
        CardView cardView = view.findViewById(R.id.cardView);

        if (mBaseElevation == 0) {
            mBaseElevation = cardView.getCardElevation();
        }

        cardView.setMaxCardElevation(mBaseElevation * 1);
        mViews.set(position, cardView);
        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View) object);
        mViews.set(position, null);
    }

    private void bind(CardItemString item, View view) {
        TextView titleTextView = view.findViewById(R.id.titleTextView);
        titleTextView.setText(item.getTitle());

    }
}

Your animatedSwitchButton is null because you use findViewById() on your current object, which is your MainActivity3 . This Activity doesn't contain the View with the ID fav_lot in adapter.xml though, since its layout-file is set to activity_main3.xml .

So you need to use findViewById() on the object you attached your adapter.xml to. This could be mViewPager.findViewById(R.id.fav_lot) for example, although I am not sure what your adapter.xml is actually attached to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM