android中三種onClick事件的實現,與對比

來源:互聯網
上載者:User

方式一:在activity的onCreate()方法中,嵌入如下代碼:

Button button = (Button)findViewById(R.id.button1);

button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
TextView textview = (TextView)findViewById(R.id.textView1);
textview.setText("Button");
}
});

這種方式用findviewbyid通過id執行個體化出來這個button,然後通過設定button的listener監聽對象,並同時實現介面OnClickListenter的OnClick()方法。這種方式的代碼量不多,但是在java中,物件導向的思想,關於耦合,模組化它達不到。代碼堆疊在一起,比較臃腫。

方式二:讓acticity持有TextView,並且建立類Button_Listener實現介面OnClickListener,activity中的代碼為:

public class TestOnClickActivity extends Activity {
private TextView textview;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.button1);
this.textview = (TextView)findViewById(R.id.textView1);
button.setOnClickListener(new Button_Listener(this));
}

public TextView getTextview() {
return this.textview;
}
}
類Button_Listener的代碼為:
class Button_Listener implements OnClickListener {
private TestOnClickActivity activity;

public Button_Listener(TestOnClickActivity activity) {
this.activity = activity;
}

@Override
public void onClick(View v) {
TextView textview = activity.getTextview();
textview.setText("你點擊了Button");

}
}

方式二:

在方式二中,為了改正方式一的介面實現的不規範,特別重建立立了一個類:Button_Listener。

這種方式代碼結構清晰,在為Button加入監聽方法是,只需要new Button_Listener(this)即可。但同時,我們也能夠發現,因為不屬於類TestOnClickActivity,所以類Button_Listener必須通過持有TestOnClickActivity,將其作為成員。並且,我們需要在TestOnClickActivity 中顯示的加入TextView,並書寫getTextview()方法,才能夠實現我們的程式意圖。

雖然代碼的模組化,解耦化得到了一定程度上的實現,但換來的結果是代碼更多,書寫更加繁瑣。

 

方式三:在組件檔案main.xml中,對Button加入:

android:onClick="onClick_Event"

在activity中加入以下代碼:

public void onClick_Event(View view) {
TextView textview = (TextView)findViewById(R.id.textView1);
textview.setText("Button");
}

在方式三種,我們只需要在TestOnClickActivity 中增加一個成員函數onClick_Event(),並在組件檔案中加入對其的使用描述即可。

代碼結構簡單,清晰,代碼量也大大減少,並且通過xml檔案的可配置性,增長了工程的可維護性,模組化進一步增強!

 

參考:http://blog.sina.com.cn/s/blog_7013d1fe01014t3o.html

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.