Cannot refer to a non-final variable timePicker inside an inner class defined in a different method.where is the inner class??
public class MainActivity extends Activity {
TimePicker timePicker;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TimePicker timePicker = (TimePicker)findViewById(R.id.timePicker);
timePicker.setIs24HourView(true);
//--Button view---
Button btnOpen = (Button)findViewById(R.id.btnSet);
btnOpen.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Toast.makeText(getBaseContext(),
"Time selected:" +
timePicker.getCurrentHour() +
":" + timePicker.getCurrentMinute(),
Toast.LENG开发者_如何转开发TH_SHORT).show();
}
});
}
}
somebody explain me plz ?
public class MainActivity extends Activity {
TimePicker timePicker;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TimePicker timePicker = (TimePicker)findViewById(R.id.timePicker);
timePicker.setIs24HourView(true);
//--Button view---
Button btnOpen = (Button)findViewById(R.id.btnSet);
btnOpen.setOnClickListener(new OnClickListener() // <------- Inner class
{
public void onClick(View v)
{
Toast.makeText(getBaseContext(),
"Time selected:" +
timePicker.getCurrentHour() +
":" + timePicker.getCurrentMinute(),
Toast.LENGTH_SHORT).show();
}
});
You're creating an anonymous class that extends the abstract OnClickListenerClass by providing an onClick method.
To fix, declare timePicker as final.
final TimePicker timePicker = (TimePicker)findViewById(R.id.timePicker);
精彩评论