ImageButton的焦點和事件處理 – Android移動開發技術文章_手機開發 Android移動開發教學課程

Java代碼 
import android.app.Activity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.ImageButton; 
import android.widget.TextView; 
/**
 * ImageButton的焦點和事件處理
 *
 */ 
public class ActivityMain extends Activity { 
    private ImageButton myImageButton ; 
    private Button myButton; 
    private TextView myTextView; 
     
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
         
        //創建三個組件 
        myImageButton = (ImageButton)findViewById(R.id.myImageButton); 
        myButton = (Button)findViewById(R.id.myButton); 
        myTextView = (TextView)findViewById(R.id.myTextView1); 
         
        //通過OnFocusChangeListener來響應ImageButton的onFocus事件 
        myImageButton.setOnFocusChangeListener(new ImageButton.OnFocusChangeListener() { 
            public void onFocusChange(View v, boolean hasFocus) { 
                //如果ImageButton得到焦點onFocus則改變ImageButton的圖片 
                if(hasFocus==true) { 
                    //更改狀態說明 
                    myTextView.setText("圖片按鈕狀態為:Got Focus"); 
                    //更改按鈕背景圖片 
                    myImageButton.setImageResource(R.drawable.iconfull); 
                } else { 
                    myTextView.setText("圖片按鈕狀態為: Lost Focus"); 
                    myImageButton.setImageResource(R.drawable.iconempty); 
                } 
            } 
        }); 
         
        //通過onClickListener來響應ImageButton的onClick事件 
        myImageButton.setOnClickListener(new ImageButton.OnClickListener(){ 
            public void onClick(View v) { 
                //如果ImageButton狀態為onClick則改變ImageButton的圖片和說明 
                myTextView.setText("圖片按鈕狀態為: Got Click"); 
                myImageButton.setImageResource(R.drawable.iconfull); 
            } 
        }); 
         
        //通過onClickListener來響應Button的onClick事件 
        myButton.setOnClickListener(new Button.OnClickListener(){ 
            public void onClick(View v) { 
                //如果Button狀態為onClick改變ImageButton圖片 
                myTextView.setText("圖片按鈕狀態為:Lost Focus"); 
                myImageButton.setImageResource(R.drawable.iconempty); 
            } 
        }); 
    } 

 

作者“阿拉丁神燈”
 

發佈留言