app简单控件了解——按钮——第二种按钮点击方式——采用匿名内部类

如何为按钮添加监听方式总结

 

本文概述:

  • 本文介绍了,在Android中为控件添加监听的三种常见方式

    • 设置控件的onClick属性
    • 采用匿名内部类
    • MainActivity 实现 View.OnClickListener 接口

 

 

 

 

 

 

 

 

 

========================================================================

 

 

 

 

 

 

 

 

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btn_click_single"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="指定单独的点击监听器"
            android:textColor="#000000"
            android:textSize="15sp" />

<!--        <Button-->
<!--            android:id="@+id/btn_click_public"-->
<!--            android:layout_width="0dp"-->
<!--            android:layout_height="wrap_content"-->
<!--            android:layout_weight="1"-->
<!--            android:text="指定公共的点击监听器"-->
<!--            android:textColor="#000000"-->
<!--            android:textSize="15sp" />-->

    </LinearLayout>

    <TextView
        android:id="@+id/tv_result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="5dp"
        android:text="这里查看按钮的点击结果"
        android:textColor="#000000"
        android:textSize="15sp" />

</LinearLayout>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

package com.example.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity
{
    private TextView tv_result; // 声明一个文本视图实例

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //获取button按钮
       Button button = findViewById(R.id.btn_click_single);

       button.setOnClickListener(new View.OnClickListener()
       {
           @Override
           public void onClick(View v)
           {
               tv_result = findViewById(R.id.tv_result); // 获取名叫tv_result的文本视图

               tv_result.setText("您点击了此按钮_yes"); // 设置文本视图的文本内容

           }
       });


    }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2022-07-02 15:24  小白龙白龙马  阅读(36)  评论(0编辑  收藏  举报