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.

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