lambda表达式中的返回类型错误:无法转换为布尔值

时间:2019-02-12 07:19:58

标签: java android lambda

我需要通过触摸按钮来更改shapeType。我尝试了此方法,但出现错误,提示shapeType无法转换为布尔值。 代码:

public class MainActivity extends AppCompatActivity {

private ArFragment arFragment;

private enum ShapeType {
    GIRAFFE,
    HIPPO,
    ELEPHANT
}

private ShapeType shapeType = ShapeType.GIRAFFE;

@SuppressLint("ClickableViewAccessibility")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    arFragment = (ArFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);

    Button giraffe = findViewById(R.id.giraffebutt);
    Button hippo = findViewById(R.id.hippobutt);
    Button elephant = findViewById(R.id.elephantbutt);

    giraffe.setOnTouchListener(view -> shapeType = ShapeType.GIRAFFE);
    hippo.setOnTouchListener(view ->shapeType = ShapeType.HIPPO);
    elephant.setOnTouchListener(view ->shapeType = ShapeType.ELEPHANT);
  }
}

错误:

Bad return type in lambda expression: ShapeType cannot be converted to boolean

2 个答案:

答案 0 :(得分:1)

您的onTouch()方法现在期望返回布尔值,而您不返回任何更改如下lambda的东西。

giraffe.setOnTouchListener(
(view, motionEvent) -> {
    shapeType = ShapeType.GIRAFFE;
    return false;
});

答案 1 :(得分:0)

按钮的setOnTouchListener提供了ViewMotionEvent,并且期望返回类型为boolean

giraffe.setOnTouchListener((view, event) -> {
    shapeType = ShapeType.GIRAFFE);
    return true; // return true if event is consumed, false otherwise
});