layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="@+id/selectview"
android:layout_height="match_parent">
<ViewFlipper
android:id="@+id/viewflipper"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/head1"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/head2"/>
</ViewFlipper>
</LinearLayout>
代码
View selectview = LayoutInflater.from(mainContext).inflate(R.layout.select_view, null);
ViewFlipper viewflipper = findViewById(R.id.viewflipper);//获取ViewFlipper布局
此时我想要用viewflipper 进行操作的时候报空指针异常
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ViewFlipper.setInAnimation(android.content.Context, int)' on a null object reference
造成这种现象的原因是当前所在contentview不是我ViewFlipper所在的布局,程序找不到我的这个ViewFlipper,所以需要告诉它在哪里找,代码改成如下就可以了
View selectview = LayoutInflater.from(mainContext).inflate(R.layout.select_view, null);
ViewFlipper viewflipper = selectview.findViewById(R.id.viewflipper);