【问题标题】:Why isn't my Handler working?为什么我的处理程序不工作?
【发布时间】:2013-06-26 07:46:59
【问题描述】:

当我去运行应用程序时,一切似乎都很好,但是当我按下开始按钮时,它不显示 Hello 我什至尝试在线程之前设置文本,但它仍然没有工作。为什么会发生这种情况?

代码如下:

public class MainActivity extends Activity implements OnClickListener {
Handler mHandler;
Button enter;
Button start;

TextView 显示;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    enter = (Button)findViewById(R.id.enter);
    start = (Button)findViewById(R.id.start);
    display =(TextView)findViewById(R.id.Display);

    mHandler = new Handler(){
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            Bundle bundle = msg.getData();
            String string = bundle.getString("myKey");
            display.setText(string);

        }
    };
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch(v.getId()){
    case R.id.enter:
        break;
    case R.id.start:
         Thread setText = new Thread(){

            @Override
            public void run() {
                // TODO Auto-generated method stub
                super.run();
                Message msg= Message.obtain();
                Bundle bundle = new Bundle();
                String dateString;
                dateString = "Hello";
                bundle.putString("myKey", dateString);
                msg.setData(bundle);
                mHandler.sendMessage(msg);
            }



        };
        setText.start();
        break;
    }
}

}

【问题讨论】:

  • 你遇到过错误吗?
  • 没有问题是当我运行代码然后按下开始按钮没有任何反应它应该更新文本视图打招呼但没有找到不报告任何错误。
  • 添加一些日志,例如“发送消息”、“处理消息”等
  • 为什么要使用Handler,为什么不直接改一下?
  • @Gina 它可能是某种测试或其他东西

标签: java android multithreading asynchronous


【解决方案1】:

您没有在 onCreate() 方法中的输入/开始按钮上注册监听器。打电话给 f.e.:

enter.setOnClickListener(this);

【讨论】:

  • 哦,哇,我完全忘记了。在这里,我认为这是一个处理程序问题。感谢您指出这一点。
猜你喜欢
  • 2017-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-24
  • 1970-01-01
  • 1970-01-01
  • 2014-07-20
相关资源
最近更新 更多