-1

我的应用程序中有一个导航抽屉。我想在导航抽屉标题处创建一个幻灯片。因此,我将 ViewFlipper 用于 nav_header.xml。我在 MainActivity 中使用了以下代码。但是应用程序停止了。我应该做些什么改变?

收到此错误:

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.myapp.praxi/com.myapp.praxi.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference

这是我的代码:

int[] resources = {R.drawable.prxi,
        R.drawable.prxi1,
        R.drawable.prxi2,
        R.drawable.prxi3,
};

ViewFlipper imageFlipper = (ViewFlipper) this.findViewById(R.id.view_flipper);

for (int i = 0; i < resources.length; i++) {
            ImageView imageView = new ImageView(this);
            imageView.setImageResource(resources[i]);
            imageFlipper.addView(imageView);
        }



    imageFlipper.setFlipInterval(4000);

    imageFlipper.setInAnimation(this, android.R.anim.slide_in_left); //use either the default slide animation in sdk or create your own ones
    imageFlipper.setOutAnimation(this, android.R.anim.slide_out_right);

    imageFlipper.getInAnimation().setAnimationListener(new Animation.AnimationListener() {

        public void onAnimationStart(Animation animation) {}
        public void onAnimationRepeat(Animation animation) {}
        public void onAnimationEnd(Animation animation) {

            int displayedChild = imageFlipper.getDisplayedChild();
            int childCount = imageFlipper.getChildCount();

            if (displayedChild == childCount - 1) {
                imageFlipper.stopFlipping();
            }
        }
    });

    imageFlipper.startFlipping();`

导航头文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="@android:dimen/thumbnail_height"
    android:padding="16dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark"
    android:orientation="vertical"
    android:gravity="bottom"
    android:background="@drawable/prxi"
    android:id="@+id/linear">

    <ViewFlipper
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/view_flipper">

    </ViewFlipper>

</LinearLayout>

4

1 回答 1

0

ViewFlipper是抽屉布局元素的子元素。您需要从导航抽屉的布局中找到视图,而不是从Activity的视图布局中。

例如,如果这是您的抽屉布局,您必须ViewFlipper像这样实例化:

DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ViewFlipper imageFlipper = (ViewFlipper) mDrawerLayout.findViewById(R.id.view_flipper);

希望有帮助。

于 2016-08-28T15:45:50.007 回答