关于andorid中Unable to instantiate activity问题解决!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在一个 Activity 监听另一个类变量的变化,可以通过以下几种方式实现: 1. 使用接口回调:定义一个接口,在另一个类声明一个接口类型的成员变量,并提供设置接口实例的方法。在需要监听变量变化的地方,实现接口,并在接口方法处理变量变化的逻辑。 示例代码如下: ```java // 定义接口 public interface OnVariableChangeListener { void onVariableChanged(String newValue); } // 另一个类的变量 public class AnotherClass { private String variable; private OnVariableChangeListener listener; public void setVariable(String newValue) { this.variable = newValue; if (listener != null) { listener.onVariableChanged(newValue); } } public void setOnVariableChangeListener(OnVariableChangeListener listener) { this.listener = listener; } } // 在 Activity 监听变量变化 public class MyActivity extends Activity implements OnVariableChangeListener { private AnotherClass anotherClass; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my); anotherClass = new AnotherClass(); anotherClass.setOnVariableChangeListener(this); } @Override public void onVariableChanged(String newValue) { // 处理变量变化的逻辑 } } ``` 2. 使用观察者模式:通过使用 Java 的 Observable 类和 Observer 接口,可以实现观察者模式。在另一个类继承 Observable 类,并在变量发生变化时调用 setChanged() 方法和 notifyObservers() 方法。在 Activity 实现 Observer 接口,通过 addObserver() 方法注册观察者,并在 update() 方法处理变量变化的逻辑。 示例代码如下: ```java import java.util.Observable; import java.util.Observer; // 另一个类的变量 public class AnotherClass extends Observable { private String variable; public void setVariable(String newValue) { this.variable = newValue; setChanged(); notifyObservers(newValue); } } // 在 Activity 监听变量变化 public class MyActivity extends Activity implements Observer { private AnotherClass anotherClass; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my); anotherClass = new AnotherClass(); anotherClass.addObserver(this); } @Override public void update(Observable observable, Object newValue) { // 处理变量变化的逻辑 } } ``` 以上是两种常用的方式来在一个 Activity 监听另一个类变量的变化。根据具体的需求和场景选择合适的方式进行实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值