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”.
执行代码后,您将得到一张图像。 实际上,这不仅是图像,而且是包含图像的按钮。 当您单击图像按钮时,烤面包消息将显示为“您单击图像按钮”。
翻译自: https://www.includehelp.com/android/ImageButton-Example-Code.aspx