我们可以编写一段监听器,当tab关闭时触发该监听器,强制将焦点移回到Android Studio窗口。
以下是具体代码示例:
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.DataKeys;
import com.intellij.openapi.actionSystem.impl.SimpleDataContext;
import com.intellij.openapi.actionSystem.impl.Utils;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.ui.tabs.JBTabs;
import com.intellij.ui.tabs.impl.JBTabsImpl;
import com.intellij.util.ui.UIUtil;
import javax.swing.*;
import java.awt.*;
public class FocusFixAction {
public static void install() {
JBTabsImpl tabs = UIUtil.uiTraverser(WindowManager.getInstance().getIdeFrame(null).getComponent())
.getNext(JBTabsImpl.class);
tabs.addListener(new FocusFixListener());
}
private static class FocusFixListener extends JBTabs.Listener.Adapter {
@Override
public void tabRemoved(TabInfo info) {
JComponent c = info.getComponent();
if (c == null) return;
if (c.getParent() instanceof JLayeredPane) {
c = c.getParent();
}
Rectangle cBounds = c.getBounds();
cBounds.y += 2;
if (SystemInfo.isOSX) {
// move down one more pixel to work around window manager bugs on macOS
cBounds.y += 1;
}
IdeFrame frame = IdeFrame.getActiveFrame();
if (frame == null) return;
JLayeredPane rootPane = frame.getRootPane();
if (rootPane == null) return;
JComponent focusOwner = (JComponent) KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
boolean isToolbar = c instanceof ActionToolbarImpl;
// if the current focused component is the main editor, focus the project tree view instead.
if (isToolbar || focusOwner == null || Utils.getComponentParent(focusOwner, JBTabs.class) == null) {
DataContext dataContext;
if (isToolbar) {
dataContext = new SimpleDataContext(DataKeys.PROJECT.getName(), null, DataKeys.CONTEXT_COMPONENT.getName(), c);
} else {
dataContext = DataManager.getInstance().getDataContext(rootPane);
}
ProjectView view = LangDataKeys.PROJECT_VIEW.getData(dataContext);
if (view != null) {
view.select(null, null, false);
IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> view.select(null, info.getProject(), true));