多窗口活动获取当前屏幕宽度

时间:2017-12-01 11:04:43

标签: android multi-window

在我的应用中,我根据当前的屏幕宽度制作了大量的UI 我有一个辅助方法可以做到这一点:

 /(a-z)\[[0-9]\])(a-z)?/;

但是当我调整多窗口活动的大小时,该函数会返回手机屏幕宽度,而不是当前。用户界面中断了很多。
我需要一个机制来计算活动的onCreate()中的宽度(OnGlobalLayoutListener没有帮助 - 因为很多初始化在onCreate中直接完成)

1 个答案:

答案 0 :(得分:0)

使用我的App类中的下一个方法进行管理:

  public static Point getSize(){
    Point point = new Point();
    if (Build.VERSION.SDK_INT >= 21  && LifecycleHandler.getInstance().getCurrentActivity() != null){
        DisplayMetrics metrics = new DisplayMetrics();
        LifecycleHandler.getInstance().getCurrentActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
        point.x = metrics.widthPixels;
        point.y = metrics.heightPixels;
    } else {
        ((WindowManager) appContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getSize(point);
    }

    return point;
}

LifecycleHandler在哪里

public class LifecycleHandler  implements Application.ActivityLifecycleCallbacks {

private static LifecycleHandler instance;

public static synchronized LifecycleHandler getInstance() {
    if (instance == null) {
        instance = new LifecycleHandler();
    }

    return instance;
}

private int resumed;
private int paused;
private int started;
private int stopped;

private WeakReference<Activity> activityRef;

public Activity getCurrentActivity() {
    if (activityRef != null) {
        return activityRef.get();
    }

    return null;
}

@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}

@Override
public void onActivityDestroyed(Activity activity) {
}

@Override
public void onActivityResumed(Activity activity) {
    ++resumed;
    //Logging.log(TAG, "onActivityResumed application is in foreground: " + (resumed > paused));
    if (started > stopped && resumed > paused) {

    }

    activityRef = new WeakReference<>(activity);
}

@Override
public void onActivityPaused(Activity activity) {
    ++paused;
    //Logging.log(TAG, "onActivityPaused application is in foreground: " + (resumed > paused));
}

@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}

@Override
public void onActivityStarted(Activity activity) {
    ++started;
    //Logging.log(TAG, "onActivityStarted application is visible: " + (started > stopped));
}

@Override
public void onActivityStopped(Activity activity) {
    ++stopped;
    //Logging.log(TAG, "onActivityStopped application is visible: " + (started > stopped));

    if (isInBackground()) {
    }
}

public boolean isInBackground() {
    return started <= stopped && resumed <= paused;
}

}

我们需要在App类中注册Lifecycle:

        registerActivityLifecycleCallbacks(LifecycleHandler.getInstance());