Android中,Button要呼叫onClick(點擊)事件需要透過OnClickListener來監聽

寫法有兩種:
1.自行建立OnClickListener物件

public class HelloActivity extends Activity {
    
	Button button1;
	Button button2;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        button1 = (Button) findViewById(R.id.button1);
        //設定OnClickListener
        button1.setOnClickListener(onclick);
        
        button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(onclick);
    }
    
    private OnClickListener onclick = new OnClickListener() {
		public void onClick(View v) {
			//do something
		}
	};
}

2.繼承OnClickListener

public class HelloActivity extends Activity implements OnClickListener {
    
	Button button1;
	Button button2;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        button1 = (Button) findViewById(R.id.button1);
        //設定OnClickListener
        button1.setOnClickListener(this);
        
        button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(this);
    }
    
	public void onClick(View v) {
		//do something
	}	
}
Categories: Android