Android ImageButton示例代码

这篇博客介绍了如何在Android中使用ImageButton,包括XML布局文件activity_main的设置和MainActivity.java的代码实现。注意,图像按钮的理想尺寸应为100dp宽和50dp高。点击按钮时,会显示'You Clicked Image Button'的提示信息。
摘要由CSDN通过智能技术生成

1) XML File: activity_main

1)XML文件:activity_main

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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="com.example.faraz.imagebutton_example.MainActivity">

    <ImageButton
        android:id="@+id/imageButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/finger"
        tools:layout_editor_absoluteX="130dp"
        tools:layout_editor_absoluteY="155dp" />
</android.support.constraint.ConstraintLayout>

2) File: MainActivity.java

2)文件:MainActivity.java

package com.example.faraz.imagebutton_example;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageButton;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;

public class MainActivity extends Activity {

    ImageButton imageButton;

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

        addListenerOnButton();

    }

    public void addListenerOnButton() {

        imageButton = (ImageButton) findViewById(R.id.imageButton1);

        imageButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                Toast.makeText(MainActivity.this, "You Clicked Image Button!", Toast.LENGTH_LONG).show();

            }

        });

    }

}

Note: Remember image button size should be 100dp and 50dp. You can resize it, but should not be very large.

注意:请记住,图像按钮的大小应为100dp和50dp。 您可以调整它的大小,但不要太大。

Output

输出量

After executing your code, you get an image. Actually this is not only an image, but a button containing an image. As you click on the image button a toast message is displayed as “You Clicked Image Button”.

执行代码后,您将得到一张图像。 实际上,这不仅是图像,而且是包含图像的按钮。 当您单击图像按钮时,烤面包消息将显示为“您单击图像按钮”。

Output - Android ImageButton Example Code 1
Output - Android ImageButton Example Code 2

翻译自: https://www.includehelp.com/android/ImageButton-Example-Code.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值