方案:我在XML在Android的佈局按鈕的通用監聽器?
<button android:id="@+id/firstbtn"
...
/>
<button android:id="@+id/secbtn"
...
/>
<button android:id="@+id/thirdbtn"
...
/>
In Java one way to listen to them is Button firstbtn = (Button) findViewById(R.id.firstbtn); firstbtn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Toast.makeText(getBaseContext(), "You have clicked first button", Toast.LENGTH_SHORT).show(); } });
爲第二BTN定義三個按鈕,相同的代碼必須用不同的ID重複??
我怎樣才能使它足夠通用,它可以聽所有的按鈕(說for循環),並在處理時,我應該能夠區分不同的btns。 (可能會獲得元素ID)
沒有必要分配變量,除非你要重新使用他們的東西:'(Button)findViewById(R.id.firstbtn))。setOnClickListener(mCorkyListener);' – Blrfl 2010-10-12 10:57:02
好吧,所以沒有辦法獲得除findViewBId(id)以外的按鈕對象?我認爲可能有一種方法可以將按鈕對象中的所有按鈕都作爲按鈕對象數組來獲取,並且我可以遍歷它並向其中添加一個偵聽器,每次在XML中添加按鈕時都會避免添加Java代碼。 – sat 2010-10-12 11:07:30
我不知道如何創建您的按鈕數組。無論如何,你可以通過使用view.getId() – kiki 2010-10-12 12:44:22