匿名類別可以是繼承某一個類別,或者實作出一個介面(interface)
例如
Button b = new Button("Click me!");
b.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Click me!");
}
}
);
其中ActionListener是interface
再一個例子:BMI.java (for Android)
Button button = (Button)findViewById(R.id.submit);
button.setOnClickListener(new OnClickListener(){
public void onClick(View v)
{
DecimalFormat nf = new DecimalFormat("0.00");
EditText fieldheight = (EditText)findViewById(R.id.height);
EditText fieldweight = (EditText)findViewById(R.id.weight);
double height = Double.parseDouble(fieldheight.getText().toString()) / 100;
double weight = Double.parseDouble(fieldweight.getText().toString());
double BMI = weight / (height * height);
TextView result = (TextView)findViewById(R.id.result);
result.setText("Your BMI is " + nf.format(BMI)); //把算出數值表示法統一並轉成字串
//give advice
TextView fieldsuggest = (TextView)findViewById(R.id.suggest);
if(BMI>25){
fieldsuggest.setText(R.string.advice_heavy);
}
else if(BMI<20){
fieldsuggest.setText(R.string.advice_light);
}
else{
fieldsuggest.setText(R.string.advice_average);
}
}
});
其中 OnClickListener 是一個介面
事實上,不管是setOnClickListener或是addActionListener,他們的參數都是interface,而這個動作的意思是"註冊"一個事件監聽者
事實上,不管是setOnClickListener或是addActionListener,他們的參數都是interface,而這個動作的意思是"註冊"一個事件監聽者
上面還可以寫成:
public void onCreate(Bundle savedInstanceState) {
.......
Button button = (Button)findViewById(R.id.submit);
button.setOnClickListener(calBMI);
}
private OnClickListener calBMI = new OnClickListener() //此為匿名類別 實作OnClickListener這個介面
{
public void onClick(View v)
{
DecimalFormat nf = new DecimalFormat("0.00");
EditText fieldheight = (EditText)findViewById(R.id.height);
EditText fieldweight = (EditText)findViewById(R.id.weight);
double height = Double.parseDouble(fieldheight.getText().toString()) / 100;
double weight = Double.parseDouble(fieldweight.getText().toString());
double BMI = weight / (height * height);
TextView result = (TextView)findViewById(R.id.result);
result.setText("Your BMI is " + nf.format(BMI)); //把算出數值表示法統一並轉成字串
//give advice
TextView fieldsuggest = (TextView)findViewById(R.id.suggest);
if(BMI>25){
fieldsuggest.setText(R.string.advice_heavy);
}
else if(BMI<20){
fieldsuggest.setText(R.string.advice_light);
}
else{
fieldsuggest.setText(R.string.advice_average);
}
}
};
Reference
沒有留言:
張貼留言