【发布时间】:2021-12-24 01:52:08
【问题描述】:
我正在尝试在 Android 中扩展 Button 类。我有一个flicker.java 和一个MainActivity.java。我想扩展 Button 类并向其添加类似public void flicker_with_current_color(){} 的方法,以便我可以在MainActivity.java 中使用flicker.flicker_with_current_color();。不幸的是,Android Studio 给了我错误(作为提示):
此自定义视图应改为扩展 androidx.appcompat.widget.AppCompatButton
我想做的是添加一个自定义方法,以便我可以在任何地方使用它。我知道这可以通过在MainActivity.java 中创建一个方法来完成,但我正在尝试制作一个与Android 的Button 类相同但具有更多方法的自定义Button 类。我不知道我错在哪里。
flicker.java:
package com.its.me;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.provider.CalendarContract;
import android.util.AttributeSet;
import android.widget.Button;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.Timer;
public class flicker extends Button{
public flicker(Context context) {
super(context);
}
public void flicker_with_current_color(Button btn, String color_to_flicker, String color_to_switch_back_to, int time_interval, int times_to_flicker){
for(int i=0; i<times_to_flicker; i++){
btn.setTextColor(Color.parseColor(color_to_flicker));
Timer t = new java.util.Timer();
t.schedule(
new java.util.TimerTask() {
@Override
public void run() {
btn.setTextColor(Color.parseColor(color_to_switch_back_to));
t.cancel();
}
},
time_interval
);
}
}
public void flicker_with_current_color(String color_to_flicker, String color_to_switch_back_to, int time_interval, int times_to_flicker){
for(int i=0; i<times_to_flicker; i++){
this.setTextColor(Color.parseColor(color_to_flicker));
Timer t = new java.util.Timer();
t.schedule(
new java.util.TimerTask() {
@Override
public void run() {
//this.setTextColor(Color.parseColor(color_to_switch_back_to));
t.cancel();
}
},
time_interval
);
}
}
public void flicker_with_current_color(Button btn, int total_time, int times_to_flicker, String color_to_flicker, String color_to_switch_back_to){
int time_interval = total_time/times_to_flicker;
for(int i=0; i<times_to_flicker; i++){
btn.setTextColor(Color.parseColor(color_to_flicker));
Timer t = new java.util.Timer();
t.schedule(
new java.util.TimerTask() {
@Override
public void run() {
btn.setTextColor(Color.parseColor(color_to_switch_back_to));
t.cancel();
}
},
time_interval
);
}
}
}
【问题讨论】:
-
This custom view should extend androidx.appcompat.widget.AppCompatButton instead- 这只是一个警告,但最好使用AppCompat版本的Button以实现向后兼容性。请参阅here。当涉及到flicker按钮时 - 完全预期的行为是什么,您提供的代码是否有效?如果不是,那么发生了什么?请改进您的问题。 -
@sweak,非常感谢!这么晚才回复很抱歉。代码不起作用。当我单击按钮时应用程序崩溃。我只是想为按钮添加一些功能,但我无法在 MainActivity.java 中使用它们。我希望 ExtendedButton 闪烁其参数中的时间和颜色,例如
ExtendedButton.flicker_with_current_color(...);。在 XML 中,我想像 Android 的 Button 类一样添加它,例如<ExtendedButton.../>。在问题中,闪烁类是ExtendedButton。我怎样才能做到这一点?
标签: java android class android-widget extends