Android开发:Button获取焦点

Button默认是无法获取焦点的,通过添加如下属性可以时Button获取焦点:

android:focusable="true" 
           android:focusableInTouchMode="true"

不过这样会带来一个问题,就是在第一次点击Button时,Button获得焦点,但是不响应点击事件,第二次点击时响应点击事件。

解决需要两次点击Button,才能响应的问题就是在为Button设置焦点监听器,并在监听器中响应与Button的点击事件,如下:

camera.setOnFocusChangeListener(new OnFocusChangeListener() {
     
     @Override
     public void onFocusChange(View v, boolean hasFocus) {
      // TODO Auto-generated method stub
      if(hasFocus){
       Intent it = new Intent(TaskOperationActivity.this, ImageReportActivity.class);
       it.putExtra("taskID", task.getId());
       it.putExtra("serialNo", camera.getTag().toString());
       for(int i = 0; i < elementImages.size(); i++){
        if(elementImages.get(i).getSerialNo().equals(camera.getTag().toString())){
         Bundle bd = new Bundle();
         bd.putSerializable("elementValue", elementImages.get(i));
         LoggerUtils.d("图片元素:", elements.get(i).toString());
         it.putExtra("bd", bd);
         break;
        }
       }
       startActivityForResult(it, MORE_PICTURE);
      }
     }
    });
    camera.setOnClickListener(new OnClickListener() {
     @Override
     public void onClick(View v) {
      // TODO Auto-generated method stub
      Intent it = new Intent(TaskOperationActivity.this, ImageReportActivity.class);
      it.putExtra("taskID", task.getId());
      it.putExtra("serialNo", camera.getTag().toString());
      for(int i = 0; i < elementImages.size(); i++){
       if(elementImages.get(i).getSerialNo().equals(camera.getTag().toString())){
        Bundle bd = new Bundle();
        bd.putSerializable("elementValue", elementImages.get(i));
        LoggerUtils.d("图片元素:", elements.get(i).toString());
        it.putExtra("bd", bd);
        break;
       }
      }
      startActivityForResult(it, MORE_PICTURE);
     }
    });

你可能感兴趣的:(Android开发:Button获取焦点)