android中的ColorPicker NullPointerException

时间:2012-06-22 12:19:03

标签: android color-picker

我正在使用这个file来选择颜色,这是一个不错的对话框,我正在使用以下代码

public class Main extends Activity implements
        ColorPickerDialog.OnColorChangedListener {

    Button b;
    Context c = this;
    ColorPickerDialog.OnColorChangedListener cc;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        b = (Button) findViewById(R.id.button1);
        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                new ColorPickerDialog(c, cc, "tag", 16777215, 0).show();

            }
        });
    }

    @Override
    public void colorChanged(String key, int color) {
        Log.d("debug", "key is " + key + " color is " + color);

    }
}

在我的main.xml中只有一个按钮。 当我点击按钮并出现对话框时,此代码工作正常,但是当我选择一种颜色NullPointerException即将到来时,我不知道为什么,任何帮助都会感激不尽。此致

2 个答案:

答案 0 :(得分:1)

在你的情况下,

Context c = this;
ColorPickerDialog.OnColorChangedListener cc;

都是 null

new ColorPickerDialog(c, cc, "tag", 16777215, 0).show();

所以,这一行导致 NPE ..

答案 1 :(得分:0)

我将我的代码更改为有效的代码,我需要在onCreate内部创建onColorChangedListener

public class Main extends Activity  {
Button b;
OnColorChangedListener cc;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    cc=new OnColorChangedListener() {

        @Override
        public void colorChanged(String key, int color) {
            Log.d("tag", "key is " + key + " color is " + color);

        }
    };
    b = (Button) findViewById(R.id.button1);
    b.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            new ColorPickerDialog(Main.this, cc, "tag", 16777215, 0).show();

        }
    });
}
}

reference