xml的onclick

来源:互联网 发布:淘宝优惠券图片素材 编辑:程序博客网 时间:2024/04/27 20:22

布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >


    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />


    <Button 
        android:id="@+id/btn1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="按钮1"
        android:onClick="mOnButton"/>
    
    <Button 
        android:id="@+id/btn2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="按钮2"
        android:onClick="mOnButton"/>
    
</LinearLayout>


主界面:

package com.issay;


import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;


public class Test02Activity extends Activity {
/** Called when the activity is first created. */




private Button btn1, btn2;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);




btn1 = (Button) findViewById(R.id.btn1);
btn2 = (Button) findViewById(R.id.btn2);
}


public void mOnButton(View v) {


switch (v.getId()) {
case R.id.btn1:
Toast.makeText(this, "按钮1", Toast.LENGTH_LONG).show();
break;
case R.id.btn2:
Toast.makeText(this, "按钮2", Toast.LENGTH_LONG).show();
break;
}
}
}

效果图如下:点击按钮1时弹出Toast显示按钮1.点击按钮2相同



原创粉丝点击