我决定使用一个简单的循环而不是硬代码来优化我的代码,因为以前我分别实现了每个PickView,而且效果很好。

这是个有问题的地方:

pick = new PickView[9];
int id;
for(int i = 0; i < pick.length; i++) {
    id = getResources().getIdentifier("pick_" + i, "id", getPackageName());
    pick[i] = (PickView)findViewById(id);
    pick[i].setOnTouchListener(this); //this is MainActivity, line:54
}


...在其中我意外收到NullPointerException:

ERROR/AndroidRuntime(8450): FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.***}: java.lang.NullPointerException
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
    at android.app.ActivityThread.access$2300(ActivityThread.java:125)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:123)
    at android.app.ActivityThread.main(ActivityThread.java:4627)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:521)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
    at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.NullPointerException
    at com.***.onCreate(MainActivity.java:54)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
    ... 11 more


我附上一个PickView类:

public class PickView extends RelativeLayout {

    private TextView textView;
    private ImageView imageView;
    private String text;

    public PickView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PickView);
        text = a.getString(R.styleable.PickView_text);

        LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.pick_view, this);
        textView = (TextView)findViewById(R.id.pick_text);
        imageView = (ImageView)findViewById(R.id.pick_bg);
    }

    public void setText(String text) {
        textView.setText(text);
    }

    public void activate(boolean isActive) {
        if (isActive)
            imageView.setImageResource(R.drawable.pick_active);
        else
            imageView.setImageResource(R.drawable.pick);
    }
}


我将不胜感激!

最佳答案

只是一个小问题,您是否有pick_0资源?

而且无论如何,您应该检查您是否确实获得了ID,并且返回的PickView不为null?

07-27 13:43