(1)通过布局文件中添加onclike时间来实现
<Button
android:id ="@+id/login3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text = "@string/button_name3"
android:onClick="onClickbutton3"
//在activity中的代码
//方法一、通过在布局文件中设置onclike事件进行登陆
public void onClickbutton3 (View view){
Toast.makeText(MainActivity.this, "you have clicked Button3", Toast.LENGTH_SHORT).show();}
(2)通过内部类来实现
loginButton1 = (Button) findViewById(R.id.login1);
方法二、通过内类来实现登陆
loginButton1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String text = "我登录进去啦,呀呀呀";
Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT).show();//Toast.LENGTH_SHORT信息的显示时间为2秒
}
});
(3)通过外部类来实现
//方法三、通过自定义外部类来实现登陆
loginButton2.setOnClickListener(new MyListener());
}
class MyListener implements View.OnClickListener {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"you have clicked Button2", Toast.LENGTH_SHORT).show();
}
}
整体的布局代码如下:
<Button
android:id = "@+id/login1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text = "@string/button_name1"
/>
<Button
android:id ="@+id/login2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text = "@string/button_name2"
/>
<Button
android:id ="@+id/login3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text = "@string/button_name3"
android:onClick="onClickbutton3"
/>
整体的方法实现代码如下:
package com.example.zyy.wuziqi;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button loginButton1;
private Button loginButton2;
private Button loginButton3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//方法一、通过在布局文件中设置onclike事件进行登陆
public void onClickbutton3 (View view){
Toast.makeText(MainActivity.this, "you have clicked Button3", Toast.LENGTH_SHORT).show();
}
//方法二、通过匿名内部类进行实现loginButton1
loginButton1 = (Button) findViewById(R.id.login1);
loginButton1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String text = "我登录进去啦,呀呀呀";
Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT).show();//Toast.LENGTH_SHORT信息的显示时间为2秒
}
});
//方法三、通过自定义外部类来实现登陆
loginButton2.setOnClickListener(new MyListener());
}
class MyListener implements View.OnClickListener {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"you have clicked Button2", Toast.LENGTH_SHORT).show();
}
}
}