In this topic, I will show you how to listen the button with xml layout file.
The sample code is following:
In MainActivity.java:
package com.example.onclicktest; import com.example.onclicktest.R; import android.app.Activity; import android.widget.Toast; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); this.setContentView(R.layout.activity_main); } /**Called when button clicked*/ public void onClick(View view){ if(view.getId() == R.id.btn_test_click){ Toast.makeText(this, "Button Clicked.", Toast.LENGTH_SHORT).show(); }//if(view.getId() == R.id.btn_write_test_file) } }
In avtivity_main.xml:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <Button android:id="@+id/btn_test_click" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_centerVertical="true" android:text="TestBotton" android:onClick="onClick" /> </RelativeLayout>The callback function has two condition:
1. the method must be 'public'.
2. the parameter of the method must only be 'View'.
沒有留言 :
張貼留言