You can do both forms, both in XML and via code.
The advantage of being via XML is that you do not write so much in the code.
ImageButton:
ImageButton imageButton = new ImageButton(this);
imageButton.setBackgroundColor(getResources().getColor(android.R.color.transparent));
File file = new File("caminho para a imagem");
Bitmap bmImg = BitmapFactory.decodeFile(file.getPath());
imageButton.setImageBitmap(bmImg);
//Se quiser algum tamanho especifico
ViewGroup.LayoutParams layoutParams = new ActionBar.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
imageButton.setLayoutParams(layoutParams);
//aí você adiciona essa imagem onde quiser, num ViewGroup
layoutPai.addView(imageButton);
Via XLM:
Imagebutton.xml file
<?xml version="1.0" encoding="utf-8"?>
<ImageButton xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/transparent"
android:id="@+id/imageButton" />
In the code:
ImageButton imageButton = (ImageButton)LayoutInflater.from(this).inflate(R.layout.imagebutton, null);
where it is null
above, you can pass the parent, which will be ViewGroup
File file = new File("caminho para a imagem");
Bitmap bmImg = BitmapFactory.decodeFile(file.getPath());
imageButton.setImageBitmap(bmImg);
//aí você adiciona essa imagem onde quiser, num ViewGroup
layoutPai.addView(imageButton);