使用setBackgroundResource()时出现NullPointerException

时间:2015-09-11 11:33:56

标签: android xml image android-layout gridview

我正在开发一个Android应用程序来在网格中显示图像。我按照youtube tutorial中列出的步骤操作。在运行应用程序时,getview方法遇到NullpointerException。 我无法弄清楚这个例外的原因。你能帮我弄清楚出了什么问题吗?

是个例外
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setBackgroundResource(int)' on a null object reference

activity_main.xml中

<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=".MainActivity" android:id="@+id/container">

<GridView
android:id="@+id/grid_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="80dp"
android:horizontalSpacing="10dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp">

</GridView>

<ImageView
    android:id="@+id/expanded_image"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:contentDescription="@string/app_name"
    android:visibility="invisible"
    />
</FrameLayout>

single_grid_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:padding="5dp">

<ImageView
    android:id="@+id/thumb"
    android:layout_width="72dp"
    android:layout_height="72dp"
    android:layout_gravity="center_horizontal"
    android:contentDescription="@string/app_name"/>
</LinearLayout>

MainActivity.Java

public class MainActivity extends Activity {

private GridView gv;
private Animator mCurrentAnimator;
private int mShortAnimationDuration;
private int j=0;

private GestureDetector detector;
private static final int SWIPE_MIN_DISTANCE=120;
private static final int SWIPE_THRESHOLD_VELOCITY=200;

private int thumb[] = {
        R.drawable.chrysanthemum,R.drawable.desert, R.drawable.hydrangeas, R.drawable.jellyfish, R.drawable.koala, R.drawable.lighthouse, R.drawable.penguins, R.drawable.tulips
};

private ImageView expandedImageView;


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

    detector = new GestureDetector(this, new SwipeGestureDetector());

    gv = (GridView) findViewById(R.id.grid_view);
    gv.setAdapter(new ImageAdapter(this));
    gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View v, int pos, long id) {

            j = pos;
            zoomImageFromThumb(v, thumb[pos]);

        }
    });

    mShortAnimationDuration = getResources().getInteger(android.R.integer.config_shortAnimTime);

}

class ImageAdapter extends BaseAdapter {

    private LayoutInflater layoutInflater;

    public ImageAdapter(MainActivity activity){
        layoutInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return thumb.length;
    }

    @Override
    public Object getItem(int pos) {
        return pos;
    }

    @Override
    public long getItemId(int pos) {
        return pos;
    }

    @Override
    public View getView(int pos, View convertView, ViewGroup parent) {

        View listItem = convertView;
        int p = pos;

        if(listItem == null) {
            Log.d("Debug","1");
            listItem = layoutInflater.inflate(R.layout.single_grid_item, null);
        }
        Log.d("Debug","2");
        ImageView iv = (ImageView) findViewById(R.id.thumb);
        Log.d("Debug","3");

        iv.setBackgroundResource(thumb[p]);
        Log.d("Debug", "4");
        return listItem;
    }
}

private void zoomImageFromThumb(final View thumbView, int imageResId) {
    if(mCurrentAnimator != null){
        mCurrentAnimator.cancel();
    }

    expandedImageView = (ImageView) findViewById(R.id.expanded_image);

    expandedImageView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (detector.onTouchEvent(event)) {
                return true;
            } else {
                return false;
            }

        }
    });

    expandedImageView.setImageResource(imageResId);

    final Rect startBounds = new Rect();
    final Rect finalBounds = new Rect();
    final Point globalOffSet = new Point();

    thumbView.getGlobalVisibleRect(startBounds);
    findViewById(R.id.container).getGlobalVisibleRect(finalBounds, globalOffSet);

    startBounds.offset(-globalOffSet.x, globalOffSet.y);
    finalBounds.offset(-globalOffSet.x, globalOffSet.y);

    float startScale;

    if((float) finalBounds.width()/finalBounds.height() > startBounds.width()/startBounds.height()) {

        startScale = (float) startBounds.height() / finalBounds.height();
        float startWidth = startScale * finalBounds.width();
        float deltaWidth = (startWidth - startBounds.width()) / 2;
        startBounds.left -= deltaWidth;
        startBounds.right += deltaWidth;

    }else {

        startScale = (float) startBounds.width() / finalBounds.width();
        float startHeight = startScale * finalBounds.height();
        float deltaHeight = (startHeight - startBounds.height())/2;
        startBounds.top -= deltaHeight;
        startBounds.bottom += deltaHeight;

    }

    thumbView.setAlpha(0f);
    expandedImageView.setVisibility(View.VISIBLE);

    expandedImageView.setPivotX(0f);
    expandedImageView.setPivotY(0f);

    AnimatorSet set = new AnimatorSet();

    set.play(ObjectAnimator.ofFloat(expandedImageView, View.X, startBounds.left, finalBounds.left)).with(ObjectAnimator.ofFloat(expandedImageView, View.Y, startBounds.top, finalBounds.top)).with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_X, startScale, 1f)).with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_Y, startScale, 1f));

    set.setDuration(mShortAnimationDuration);
    set.setInterpolator(new DecelerateInterpolator());
    set.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            mCurrentAnimator = null;
        }

        @Override
        public void onAnimationCancel(Animator animation) {
            mCurrentAnimator = null;
        }
    });

    set.start();
    mCurrentAnimator = set;

    final float startScaleFinal = startScale;
    expandedImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(mCurrentAnimator != null){
                mCurrentAnimator.cancel();
            }
            AnimatorSet set = new AnimatorSet();

            set.play(ObjectAnimator.ofFloat(expandedImageView, View.X, startBounds.left))
                    .with(ObjectAnimator.ofFloat(expandedImageView, View.Y, startBounds.top))
                    .with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_X, startScaleFinal))
                    .with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_Y, startScaleFinal));



            set.setDuration(mShortAnimationDuration);
            set.setInterpolator(new DecelerateInterpolator());
            set.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    thumbView.setAlpha(1f);
                    expandedImageView.setVisibility(View.GONE);
                    mCurrentAnimator = null;
                }

                @Override
                public void onAnimationCancel(Animator animation) {
                    thumbView.setAlpha(1f);
                    expandedImageView.setVisibility(View.GONE);
                    mCurrentAnimator = null;
                }
            });

            set.start();
            mCurrentAnimator = set;
        }
    });

}

private class SwipeGestureDetector extends GestureDetector.SimpleOnGestureListener  {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
    try{

        if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY){
            if(thumb.length > j) {
                j++;

                if(j < thumb.length) {
                    expandedImageView.setImageResource(thumb[j]);
                    return true;
                } else {
                    j = 0;
                    expandedImageView.setImageResource(thumb[j]);
                    return true;
                }

            }
        } else if(e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY){

            if( j >0 ) {
                j--;
                expandedImageView.setImageResource(thumb[j]);
                return true;
            } else {
                j=  thumb.length-1;
                expandedImageView.setImageResource(thumb[j]);
                return true;
            }
        }
    }catch (Exception e){
        e.printStackTrace();
    }


    return false;
}
}
}

1 个答案:

答案 0 :(得分:1)

替换
     ImageView iv = (ImageView)findViewById(R.id.thumb);

ImageView iv = (ImageView)listItem.findViewById(R.id.thumb);

因为您的listItem视图包含对您的布局single_grid_item

的引用