setEnabled() 函数是否可以被覆盖,如果是这样,如何覆盖?


public class AppaSwitch extends AppCompatImageButton implements View.OnClickListener {
@Override
public void onClick(View v) {
}
}

像上面code有没有办法覆盖android中的setEnabled()函数。下面是一个例子,但我没有看到这样的方法

public class AppaSwitch extends AppCompatImageButton implements View.OnEnabled {
@Override
public void OnEnabled(View v) {
}
}

或者有没有其他方法可以做到这一点?

setEnabled() 是 View class 的方法,AppCompatImageButton已经扩展ViewClass,所以你可以像下面这样直接覆盖:

public class AppaSwitch extends AppCompatImageButton {
@Override
public void setEnabled(boolean enabled) {
//your piece of code
//if you want to remove below line to remove the function of super class.
super.setEnabled(enabled);
}
}

你需要扩展View类才能覆盖setEnabled,然后定义自己的接口来实现这样的onEnabled回调方法。

但是,我认为您应该使用Switch或其他CompoundButton来确定onCheckChanged

或者,您可以使用常规单击侦听器和一些EventBus库来通知视图启用

创建一个自定义开关,如下所示,

public class AppCustomSwitch extends AppCompatImageButton {
private OnEnabledListener listener;
public AppCustomSwitch(Context context) {
super(context);
}
public AppCustomSwitch(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AppCustomSwitch(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
if(enabled){
listener.OnEnabled(this);
}
}
public void setOnEnabledListener(OnEnabledListener listener) {
this.listener = listener;
}
public interface OnEnabledListener{
public void OnEnabled(View v);
}
}

并使您的活动/片段实现AppCustomSwitch.OnEnabledListener

public class TestActivity extends AppCompatActivity implements AppCustomSwitch.OnEnabledListener{
private AppCustomSwitch customSwitch;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
customSwitch = findViewById(R.id.custom_switch);
customSwitch.setOnEnabledListener(this);
}
@Override
public void OnEnabled(View v) {
// your stuff here
}
}

你不能seEnabled();方法,因为它是一个二传手方法而不是一个interface方法

最新更新