代码运行错误

来源:4-4 匿名内部类方式

日落长安归

2021-08-12 17:06:52

package com.example.testapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class ButtonActivity extends AppCompatActivity {

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

//1.获取按钮
Button btn1 = findViewById(R.id.btn1);
//点击事件:被点击时被触发的事件
MyClickListener mcl = new MyClickListener();
btn1.setOnClickListener(mcl); //为按钮注册点击事件监听器

Button btn2 = findViewById(R.id.btn2);
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.e("TAG","=========匿名内部类========");
}
});
}

class MyClickListener implements View.OnClickListener{
@Override
public void onClick(View view){
//在控制台输出一条语句
Log.e("TAG","刚刚点击的按钮时注册了内部类监听器对象的按钮");
}
}
}

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ButtonActivity">

<Button
android:id="@+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="通过自定义内部类实现点击事件"
android:background="#ff00ff"></Button>

<Button
android:id="@+id/bt2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="通过匿名内部类实现点击事件"></Button>

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="通过当前Activity去实现点击事件接口"></Button>

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="在xml文件中绑定"></Button>

</LinearLayout>

问题描述:

代码运行错误,但是不知道原因为什么?

http://img.mukewang.com/climg/6114e49309ea9e9319041022.jpg

http://img.mukewang.com/climg/6114e4930983253119041022.jpg

给button命名了而且根据视频完成了代码。


写回答

2回答

LovelyChubby

2021-08-13

  1. 你电脑上的中文编码 出问题了,看不出报错原因

  2. 可以点击android-studio右下角的UTF-8切换编码格式为GBK

    http://img.mukewang.com/climg/6116859d0902e48208140096.jpg

0

日落长安归

提问者

2021-08-12

http://img.mukewang.com/climg/6114e7e5090207e019041022.jpg

0

0 学习 · 2907 问题

查看课程