I want open the battery usage setting by click a button. The code is this:

Button btnusage = (Button)findViewById(R.id.batteryusage);
Button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        openOptionsBatt();
    }
});

And the method:

public openOptionsBatt(View v) {
    Intent intentBatteryUsage = new Intent(Intent.ACTION_POWER_USAGE_SUMMARY);        
    startActivity(intentBatteryUsage);
}

The application crash onCreate.. Why?

有帮助吗?

解决方案

Try changing

Button btnusage = (Button)findViewById(R.id.batteryusage);
Button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        openOptionsBatt();
    }
});

to

Button btnusage = (Button)findViewById(R.id.batteryusage);
btnusage.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        openOptionsBatt();
    }
});

Note that in the second code snippet you're using btnusage, not Button. You want the OnClickListener to attach to your instance of Button not the class Button itself.

Also, you're calling openOptionsBatt(); with passes 0 arguments, when your method public openOptionsBatt(View v) requires 1. I would change public openOptionsBatt(View v) to take 0 arguments. You're also missing the keyword void in your method signature.

public void openOptionsBatt()

其他提示

It seems that:

public openOptionsBatt(View v) { ... }

takes a View "v" but when you use the method itself you forget to set the view:

openOptionsBatt();

Based on the changes suggested previously as well as this, try changing your code to the following:

Button btnusage = (Button) findViewById(R.id.batteryusage);
btnusage.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        openOptionsBatt(v);
    }
});

Hope this helps.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top