我在布局中有一个文本视图。我的要求是当我按下或聚焦它时,文本应该加粗。否则它应该使用普通字体。我该如何实现它?
使用以下代码
TextView name=((TextView)findViewById(R.id.TextView01));
name.hasFocus();
name.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(hasFocus)
((TextView)findViewById(R.id.TextView01)).setTypeface(Typeface.DEFAULT_BOLD);
else
((TextView)findViewById(R.id.TextView01)).setTypeface(Typeface.DEFAULT);
}
});
name.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
((TextView)findViewById(R.id.TextView01)).setTypeface(Typeface.DEFAULT_BOLD);
return false;
});public class ClickTextView extends android.support.v7.widget.AppCompatTextView {
Rect rect;
public ClickTextView(Context context) {
super(context);
init();
}
public ClickTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ClickTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init(){
setClickable(true);
rect = new Rect();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN
|| action == MotionEvent.ACTION_HOVER_ENTER){
this.setTypeface(Typeface.DEFAULT_BOLD);
getHitRect(rect);
}else if (action == MotionEvent.ACTION_MOVE){
boolean inView = rect.contains(getLeft() + (int) event.getX(), getTop() + (int) event.getY());
this.setTypeface(inView ? Typeface.DEFAULT_BOLD : Typeface.DEFAULT);
}else if (action == MotionEvent.ACTION_UP
|| action == MotionEvent.ACTION_CANCEL
|| action == MotionEvent.ACTION_HOVER_EXIT
|| action == MotionEvent.ACTION_OUTSIDE) {
this.setTypeface(Typeface.DEFAULT);
}
return super.onTouchEvent(event);
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
super.onFocusChanged(focused, direction, previouslyFocusedRect);
if (focused) this.setTypeface(Typeface.DEFAULT_BOLD);
else this.setTypeface(Typeface.DEFAULT);
}
}
随意在任何地方使用它。