0

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

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,我不知道为什么,任何帮助将不胜感激。问候

4

2 回答 2

1

在你的情况下,

Context c = this;
ColorPickerDialog.OnColorChangedListener cc;

两者都是null

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

所以,这条线导致NPE ..

于 2012-06-22T12:20:26.437 回答
0

我将代码更改为有效的代码,我需要在这样的内部进行onCreateonColorChangedListener

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();

        }
    });
}
}

参考

于 2012-06-22T12:45:19.747 回答