经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 移动开发 » Android » 查看文章
Button控件的点击事件
来源:cnblogs  作者:小付园丁  时间:2019/3/18 8:42:29  对本文有异议

Java的代码

主要重点:

  • findViewById();
  • OnClickListener()

                  

 1 package com.example.admin.myapplication;
 2 
 3 import android.support.v7.app.AppCompatActivity;
 4 import android.os.Bundle;
 5 import android.view.View;
 6 import android.widget.Button;
 7 import android.widget.TextView;
 8 public class MainActivity extends AppCompatActivity {
 9     TextView t;
10     Button but1;
11     Button but2;
12     @Override
13     protected void onCreate(Bundle savedInstanceState) {
14         super.onCreate(savedInstanceState);
15         setContentView(R.layout.activity_main);
16         t =findViewById(R.id.t1);
17         but1=findViewById(R.id.b1);
18         but2 =findViewById(R.id.b2);
19         //通过findViewById()初始化控件
20 
21         //点击事件方法1
22         but2.setOnClickListener(new View.OnClickListener() {
23             @Override
24             public void onClick(View view) {
25                 t.setText("点击了"+ but2.getText().toString());
26             }
27         });
28     }
29     //点击事件方法2
30     public void b(View view){
31         t.setText("点击了"+ but1.getText().toString());
32     }
33 }

xml文件主要是设计手机界面(UI)

 重点:控件的运用 (Button TextView)以及属性的设置

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3 xmlns:app="http://schemas.android.com/apk/res-auto"
 4 xmlns:tools="http://schemas.android.com/tools"
 5 android:layout_width="match_parent"
 6 android:layout_height="match_parent"
 7 tools:context=".MainActivity"
 8 android:orientation="vertical"
 9     >
10 <TextView
11     android:layout_height="wrap_content"
12     android:layout_width="match_parent"
13     android:id="@+id/t1"
14     android:text="input"
15     android:textSize="25sp"
16     android:gravity="center"
17     />
18 <Button
19     android:layout_width="match_parent"
20     android:layout_height="wrap_content"
21     android:id="@+id/b1"
22     android:text="按钮1"
23     android:onClick="b"
24     />
25 <Button
26     android:layout_width="match_parent"
27     android:layout_height="wrap_content"
28     android:id="@+id/b2"
29     android:text="按钮2"
30     />
31 </LinearLayout>

app界面如图

 

原文链接:http://www.cnblogs.com/xfweb/p/10544315.html