与处理程序设计模式相关的问题

时间:2014-01-17 14:58:29

标签: android event-handling handler

我有一个实现了侦听器的类,并且根据侦听器中的方法调用,我将更新相应活动中的数据。为此,我有兴趣为每个活动使用不同的处理程序。 因为,每个活动中的处理程序类都是静态的,因此处理程序对象在活动中是非静态的。 那么,问题是如何使用这些活动的处理程序向他们发送消息。帮助

这是我的课程之一,我将从另一个类更新数据:怎么做?

public class HandlerActivity extends Activity {
TextView tv;
int counter;
Handler handler = new HandlerExtension(this);


//handler static class
private static class HandlerExtension extends Handler {
    private final WeakReference<HandlerActivity> targetActivity;
    //constructor
    HandlerExtension(HandlerActivity activity){
        this.targetActivity = new WeakReference<HandlerActivity>(activity);
    }

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        HandlerActivity activity = targetActivity.get();

        if(activity != null){
            final String data = msg.getData().getString("counter");//gettting msg data
            activity.tv.setText(data);
        }
    }
}//HandlerExtension


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.handler_activity);
    Button startB = (Button) findViewById(R.id.button1);
    tv = (TextView) findViewById(R.id.textView1);

    final Runnable runnable = new Runnable() {//object to be executed in the thread
        @Override
        public void run() {
            counter+=10;
            String result = String.valueOf(counter);
            Message msg = new Message();
            Bundle bundle = new Bundle();
            bundle.putString("counter", result);
            msg.setData(bundle);
            handler.sendMessage(msg);//Now, updating the view from background thread via handler

            SystemClock.sleep(1000);
        }
    };

    //starting the background thread on button click
    startB.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new Thread(runnable).start();
        }
    });




}//onCreate

} // HandlerActivity

0 个答案:

没有答案