Android studio:错误: 需要常量表达式

最近将一个项目作为library,通过import Moudle导入一个新项目引用时,爆出这个错误:需要常量表达式,定位到switch。于是百度一下,解决方法为把switch case,改成if else,即:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        switch (item.getItemId()){
            case R.id.scan:
                Intent serverIntent=new Intent(this,DeviceList.class);
                startActivityForResult(serverIntent,REQUEST_CONNECT_DEVICE);
                return true;
            case R.id.discoverable:
                ensureDiscoverable();
                return true;
            case R.id.BtOpen:
                if (!mBluetoothAdapter.isEnabled()) {
                    Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(turnOn, REQUEST_ENABLE_BT);
                }
                return true;
            case R.id.BtOff:
                mBluetoothAdapter.disable();
                return true;
        }
        return false;
    }

改为:

  @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        if(item.getItemId()==R.id.scan)
        {
            Intent serverIntent=new Intent(this,DeviceList.class);
            startActivityForResult(serverIntent,REQUEST_CONNECT_DEVICE);
        }
        if(item.getItemId()==R.id.discoverable)
        {
            ensureDiscoverable();
            return true;
        }
        if(item.getItemId()==R.id.BtOpen)
        {
            if (!mBluetoothAdapter.isEnabled()) {
                Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(turnOn, REQUEST_ENABLE_BT);
            }
            return true;
        }
        if(item.getItemId()==R.id.BtOff)
        {
            mBluetoothAdapter.disable();
            return true;
        }
        return false;
    }

具体原因:
http://tools.android.com/tips/non-constant-fields.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章