1. 嵌入物件方式 new
OnClickListener()
Button button = (Button)findViewById(R.id.button1);
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { doSomething(); } });
2. 建立物件 Button_Listener 實作 OnClickListener 功能
class Button_Listener implements OnClickListener { private MainActivity activity; public Button_Listener(MainActivity activity) { this.activity = activity; } @Override public void onClick(View v) { doSomething(); } }
在Activity onCreate() 內定義事件Callback
Button button = (Button)findViewById(R.id.button1); button.setOnClickListener(new Button_Listener(this));
3.
XML 加入屬性
android:onClick="doSomething"
然後在Activity 加入方法:
然後在Activity 加入方法:
public void doSomething(View view) { }
4.
Activity 實作 OnClickListener
public class MainActivity extends Activity implements OnClickListener { ... @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button = (Button)this.findViewById(R.id.button1); button.setOnClickListener(this); } @Override public void onClick(View view) { doSomething(); } }
沒有留言:
張貼留言