Android studio 图片按钮

本文介绍如何使用XML布局文件和Java代码在Android应用中创建按钮并响应点击事件。通过ImageButton组件设置不同图片作为按钮,并使用OnClickListener监听点击,显示Toast消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

.xml文件代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">
    <ImageButton
        android:id="@+id/login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/apple"/>
    <ImageButton
        android:id="@+id/zhuce"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/banana"
        android:onClick="myClick"/>
</LinearLayout>

,java文件代码如下:

package com.example.button;

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

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageButton b=(ImageButton) findViewById(R.id.login);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast toast=Toast.makeText(MainActivity.this,"你单击了“苹果”按钮",Toast.LENGTH_SHORT);
                toast.show();
            }
        });
    }
    public void myClick(View view){
        Toast toast=Toast.makeText(MainActivity.this,"你单击了“香蕉”按钮",Toast.LENGTH_SHORT);
        toast.show();
    }
}

在这里插入图片描述
在此不做过多解释,与普通按钮类似,可看Android studio普通按钮那一篇

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值