Android Studio的Button控件的onClick属性、setOnClickListener函数与OnClickListener接口用法
添加点击事件处理函数有三种方法,一个是在Xml文件中添加onClick属性,然后在代码中添加对应的函数;二是直接在代码中添加setOnClickListener函数;三是Activity通过implements实现OnClickListener接口。
onClick属性
1、在Xml文件中添加onClick属性:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/mybutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Press Me"
android:onClick="buttonClick"/>
</RelativeLayout>
在代码中添加对应的函数:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void buttonClick(View view) {
Toast.makeText(this, "Button was clicked", Toast.LENGTH_SHORT).show();
}
}
setOnClickListener函数
2、添加setOnClickListener函数
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.mybutton);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Button was clicked", Toast.LENGTH_SHORT).show();
}
});
}
}
OnClickListener接口
3、Activity通过implements实现OnClickListener接口
public class mainActivity extends Activity implements OnClickListener{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.Button02).setOnClickListener(this);
findViewById(R.id.Button03).setOnClickListener(this);
}
public void onClick(View view) {
switch (v.getId()) {
case R.id.Button03:
Toast.makeText(MainActivity.this, "Button was clicked", Toast.LENGTH_SHORT).show();
break;
case R.id.Button02:
Toast.makeText(MainActivity.this, "Button was clicked", Toast.LENGTH_SHORT).show();
break;
}
}
……
}
学习自用,侵删。
|