• Button控件的点击事件


    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界面如图

  • 相关阅读:
    spring mvc 参数校验
    spring-boot 配置jsp
    java 多线程之取消与关闭
    spring transaction 初识
    java 读取环境变量和系统变量的方法
    每天一命令 git checkout
    每天一命令 git stash
    每天一命令 git reset
    log4j2配置详解
    专业名词及解释记录
  • 原文地址:https://www.cnblogs.com/xfweb/p/10544315.html
Copyright © 2020-2023  润新知