使用setBackgroundResource()时发生NullPointerException [英] NullPointerException on using setBackgroundResource()

查看:137
本文介绍了使用setBackgroundResource()时发生NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Android应用程序以在网格中显示图像.我正在按照 youtube教程中列出的步骤进行操作.在运行应用程序时,getview方法遇到NullpointerException. 我无法弄清楚此异常的原因.您能帮我找出问题所在吗?例外是

I am developing an android application to show images in a grid. I am following the steps listed in the youtube tutorial. On running the app, the getview method encounters a NullpointerException. I am unable to figure out the reason of this exception. Can you help me figure out what is wrong? The exception is

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

activity_main.xml

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

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

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;
}
}
}

推荐答案

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

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

使用

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

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

because your listItem view contains reference of your layout single_grid_item

这篇关于使用setBackgroundResource()时发生NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆