如何在运行时设置Android Activity中的Action Button图标?

时间:2015-04-03 22:59:24

标签: android button android-actionbar

我的ActionBar中有一个操作按钮,基本上用于指示手机上蓝牙服务的状态。我可以创建此操作按钮并切换其状态,甚至可以将图标从bluetooth_on.png更改为bluetooth_off.png,但我不知道如何设置正确的图标,基于活动首次启动时蓝牙服务的状态。

我想我需要在这里做点什么:

@Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        // Inflate the menu; this adds items to the action bar if it is present.

        getMenuInflater().inflate(R.menu.dashboard, menu);
        return true;
    }

这是我目前使用的代码:

@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.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        else if (id == R.id.action_bluetooth) 
        {
            if(bluetoothStatus == false)
            {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                if(beaconManager.isBluetoothEnabled())
                {
                    bluetoothStatus = true;
                    item.setIcon(R.drawable.bluetooth_on);
                }

            }
            else
            {
                bluetooth_mgr.disable();
                bluetoothStatus = false;
                item.setIcon(R.drawable.bluetooth_off);
            }


        }
        return super.onOptionsItemSelected(item);
    }

忽略beaconManager(我使用Estimotes beacons SDK)。布尔变量bluetoothStatus用作我的标志变量,用于检查蓝牙是ON还是OFF。如何在活动发布时使用此功能在操作按钮中设置正确的图标?

1 个答案:

答案 0 :(得分:2)

如果我理解正确,您希望在启动时将图标设置为正确的指示符。假设beaconManager在onCreate中初始化(或者在调用onCreateOptionsMenu之前),这应该适合你。

 public boolean onCreateOptionsMenu(Menu menu) 
{
    // Inflate the menu; this adds items to the action bar if it is present.

    getMenuInflater().inflate(R.menu.dashboard, menu);
    MenuItem item =  menu.findItem(R.id.action_bluetooth);
    if(item != null){
         if(beaconManager.isBluetoothEnabled())
            {
                bluetoothStatus = true;
                item.setIcon(R.drawable.bluetooth_on);
            }else{
               item.setIcon(R.drawable.bluetooth_off);
            }
    }
    return true;
}