重构Button类,实现APP在大屏幕下用遥控器遥控,界面按钮在获取焦点下显示边框

本文介绍了如何重构Button类,以便在大屏幕应用中,当使用遥控器操作时,按钮在获取焦点时能显示清晰的边框,提升用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以下为MyButton类:

package com.TouchLife.touchlife;

import android.content.Context;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;

public class MyButton extends android.widget.Button{

	public MyButton(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
	}

	public MyButton(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	public MyButton(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
	}

    private boolean focused;
	@Override
	protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
		super.onFocusChanged(focused, direction, previouslyFocusedRect);
		
		this.focused = focused;
		if(focused){
			android.view.ViewGroup.LayoutParams temp = this.getLayoutParams();
			temp.height = this.getHeight() - 1;
			temp.width = this.getWidth() - 1;
			this.setLayoutParams(temp);
		}
		else{
			android.view.ViewGroup.LayoutParams temp = this.getLayoutParams();
			temp.height = this.getHeight() + 1;
			temp.width = this.getWidth() + 1;
			this.setLayoutParams(temp);
		}
	}	




	@Override
	protected void onDraw(android.graphics.Canvas canvas) {
		//this.getba
		if(focused){
			Paint paint = new Paint();
			paint.setColor(0xeeFAC23D);
			canvas.drawLine(1, 1, this.getWidth()-1, 1, paint);
			canvas.drawLine(1, 1, 1, this.getHeight()-1, paint);
			canvas.drawLine(1, this.getHeight()-1, this.getWidth()-1, this.getHeight()-1, paint);
			canvas.drawLine(this.getWidth()-1, 1, this.getWidth()-1, this.getHeight()-1, paint);
		}
		
		super.onDraw(canvas);
	}


}

使用方法:

xml布局文件直接引用:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值