为什么代码无法运行成功?显示不全?

来源:4-7 通过xml绑定点击事件

日落长安归

2021-08-12 17:38:13

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 implements View.OnClickListener {

@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","=========匿名内部类========");
}
});

Button btn3 = findViewById(R.id.btn3);
btn3.setOnClickListener(this);
}
@Override
public void onClick(View view){
Log.e("TAG","用本类实现了OnClickListener");

}

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

public void myClick(View view){
Log.e("TAG","通过xml绑定的点击事件");
}
}

<?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"
android:orientation="horizontal">

<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/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="通过匿名内部类实现点击事件"></Button>

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

<Button
android:id="@+id/btn4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="在xml文件中绑定"
android:onClick="myClick"></Button>

<Button
android:id="@+id/btn5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="在xml文件中绑定2"
android:onClick="myClick"></Button>

</LinearLayout>

问题描述:

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

代码显示不全面,只显示了第一个,请问是为什么?

写回答

1回答

LovelyChubby

2021-08-13

1. 你跟布局的方向设置为横向了,需要设置为竖向

android:orientation="horizontal"

2. 基础课程的学习也可参考:https://www.songyubao.com/book/primary/

0

0 学习 · 2907 问题

查看课程