預先準備三個按鈕的圖像, 分別顯示normal, focused 和 pressed 三種狀態, 並且儲存到/res/drawable-mdpi/文件夾中.
修改佈局文件(/res/layout/main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<ImageButton
android:id="@+id/imagebutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/normal"
/>
</LinearLayout>
在主程序重寫setOnFocusChangeListener()和setOnClickListener(), 使用ImageButton.setImageResource加載圖像.
package com.AndroidImageButton;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
public class AndroidImageButton extends Activity {
ImageButton imageButton;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageButton = (ImageButton)findViewById(R.id.imagebutton);
imageButton.setOnClickListener(imageButtonOnClickListener);
imageButton.setOnFocusChangeListener(imageButtonOnFocusChangeListener);
}
private ImageButton.OnClickListener imageButtonOnClickListener
= new ImageButton.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
imageButton.setImageResource(R.drawable.pressed);
}
};
private ImageButton.OnFocusChangeListener imageButtonOnFocusChangeListener
= new ImageButton.OnFocusChangeListener(){
@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if (hasFocus==true)
{
imageButton.setImageResource(R.drawable.focused);
}
else
{
imageButton.setImageResource(R.drawable.normal);
}
}
};
}
此留言已被作者移除。
回覆刪除此留言已被作者移除。
回覆刪除問題解決了 我想問一下
回覆刪除有辦法靠按鈕觸發他在顯現圖片嗎??