4.2设计具有背景图的按钮—ImageButton的焦点及事件处理
目录
4.2设计具有背景图的按钮—ImageButton的焦点及事件处理
方法:ImageButton的 onFocusChange方法,onClick方法
代码:
package edu.cquptzx.ImageButton;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
publicclass ImageButtonActivity extends Activity {
private ImageButton ib;
private Button btn;
private TextView tv;
/** Called when the activity is first created. */
publicvoid onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/*Find the objects by IDs.*/
ib = (ImageButton) findViewById(R.id.imageButton);
btn= (Button) findViewById(R.id.button);
tv = (TextView) findViewById(R.id.statusText);
final String str_textView = getString(R.string.textView);
final String str_status_FOCUSED = getString(R.string.status_FOCUSED);
final String str_status_LOSTFOCUSED = getString(R.string.status_LOSTFOCUSED);
final String str_GOTCLICK = getString(R.string.status_GOTCLICK);
/*Add an listener to the ImageButton to response the OnFocus Event. */
ib.setOnFocusChangeListener(new OnFocusChangeListener()
{
publicvoid onFocusChange(View v, boolean hasFocus)
{
/*IF ImageButton's status change , replace the pic and text. */
System.out.println("A");
if( v.isFocused() == true)
{
System.out.println("B");
tv.setText(str_textView + str_status_FOCUSED);
ib.setImageResource(R.drawable.iconfull);
}
else
{
System.out.println("C");
tv.setText(str_textView + str_status_LOSTFOCUSED);
ib.setImageResource(R.drawable.iconempty);
}
}
});
ib.setOnClickListener(new OnClickListener()
{
publicvoid onClick(View v)
{
System.out.println("D");
tv.setText(str_textView + str_GOTCLICK);
ib.setImageResource(R.drawable.iconfull);
}
});
btn.setOnClickListener(new OnClickListener()
{
publicvoid onClick(View v)
{
System.out.println("E");
tv.setText(str_textView + str_status_LOSTFOCUSED);
ib.setImageResource(R.drawable.iconempty);
}
});
}
}
效果:
问题:
onFocusChange方法并没有起到作用,从LogCat里面可以看出来: