Android(安卓)studio实现按钮的点击事件
16lz
2022-03-19
main.xml中的代码如下
<?xml version="1.0" encoding="utf-8"?><android.support.v7.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="app.yu.com.test.Main"> <Button android:id="@+id/bt1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="第一种" /> <Button android:id="@+id/bt2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="第二种" /> <Button android:id="@+id/bt3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="第三种" /> <Button android:id="@+id/bt31" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="第三一种" /> <Button android:id="@+id/bt32" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="第三二种" /> <Button android:id="@+id/bt33" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="第三三种" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="第四种" android:onClick="youyiyi" tools:layout_editor_absoluteY="0dp" tools:layout_editor_absoluteX="0dp" />android.support.v7.widget.LinearLayoutCompat>
Main.java的代码如下
import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast;public class Main extends AppCompatActivity implements View.OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button btn1 = (Button)findViewById(R.id.bt1); btn1.setOnClickListener(new MyListener()); Button btn2 = (Button)findViewById(R.id.bt2); btn2.setOnClickListener(new MyListener()); Button btn3 = (Button)findViewById(R.id.bt3);// btn3.setOnClickListener(new MyListener()); btn3.setOnClickListener(this); } @Override public void onClick(View v) { Toast.makeText(getApplicationContext(),"实现点击第三个按钮",Toast.LENGTH_LONG).show();//显示时长分为
Toast.LENGTH_SHORT和Toast.LENGTH_LONG两种模式} class MyListener implements View.OnClickListener{ @Override public void onClick(View v) { int id = v.getId(); switch (id) { case R.id. bt1: Toast toast = Toast. makeText(getApplicationContext(), "点击第一个按钮", Toast. LENGTH_SHORT); toast.show(); System. out.println( "点击第一个按钮"); break; case R.id. bt2: System. out.println( "点击第二个按钮"); break; case R.id. bt3: System. out.println( "点击第三个按钮"); break; } } }}
更多相关文章
- Android中点击事件之FocusChangedListener实现步骤
- android popupwindow 中listview 无法点击问题
- Android如何监听输入框的出现和隐藏
- 2013.12.04 (6)——— android SlidingMenu之ViewPagerActivity
- 判断可用的intent和更改Drawable的透明度
- android 可编辑的下拉框 Demo
- android 4.3源码编译
- org.gradle.api.GradleException: Lint found fatal errors whil
- 如何避免输入法弹出时遮挡住按钮或输入框