gpt4 book ai didi

Android 用户界面规模

转载 作者:行者123 更新时间:2023-11-29 17:01:11 25 4
gpt4 key购买 nike

我知道 Android 系统提供了一种在整个系统上扩展 UI 的方法,但我想要类似的东西,但只适用于我的应用程序。假设在“设置”中我有一个缩放 UI 的选项,并且使用 slider 我的应用程序的 UI 只能在我的应用程序上放大或缩小。有什么想法可以轻松做到这一点吗?

更新:

我已经在 onCreate 中试过了:

private void setScale(float screenRatio) {
Resources resources = getResources();
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

Configuration configuration = resources.getConfiguration();
configuration.densityDpi = (int) (metrics.densityDpi * screenRatio);
metrics.scaledDensity = metrics.scaledDensity * screenRatio;
resources.updateConfiguration(configuration, resources.getDisplayMetrics());
}

但存在三个缺点:

  1. 我需要重新启动应用程序才能使更改生效
  2. 它只缩放 View 而不缩放字体大小
  3. 变化不是实时可见的

这是相同的 260dpi 屏幕,但具有缩放的 UI。

/image/wkzZb.png

/image/WF5rY.png

/image/GMYRA.png

/image/hTREN.png

最佳答案

这就是我找到的解决方案,这里是一个如何实现它的工作示例: https://github.com/thelong1EU/ScaleUI

<强>1。创建一个使用自定义配置对象的 ContextWraper 对象

正如我所猜测的那样,这一切都与上下文对象有关。第一步是创建一个包含所需修改的 ContextWraper 对象。您可以从此处更改语言环境和所有其他限定符或设备属性。请在此处查看完整列表: https://developer.android.com/reference/android/content/res/Configuration.html#lfields

public class ScaledContextWrapper extends ContextWrapper {

public ScaledContextWrapper(Context base) {
super(base);
}

@SuppressWarnings("deprecation")
public static ScaledContextWrapper wrap(Context context) {
Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
DisplayMetrics metrics = resources.getDisplayMetrics();

configuration.densityDpi = (int) (metrics.densityDpi * sScaleRatio);
configuration.fontScale = sScaleRatio;

if (SDK_INT > 17) {
context = context.createConfigurationContext(configuration);
} else {
resources.updateConfiguration(configuration, resources.getDisplayMetrics());
}

return new ScaledContextWrapper(context);
}

}

<强>2。设置您希望进行修改的新上下文

如果你想改变整个 Activity 的比例,你需要覆盖 attachBaseContext() 并传递修改后的 Context 对象:

@Override
protected void attachBaseContext(Context newBase) {
Context context = ScaledContextWrapper.wrap(newBase);
super.attachBaseContext(context);
}

如果您只想更改一个 fragment 甚至一个 View 的比例,您需要使用使用修改后的 Context 构造的 LayoutInflater 对象。这是缩放 fragment 的示例:

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
Context scaledContext = ScaledContextWrapper.wrap(getActivity());
LayoutInflater scaledInflater = LayoutInflater.from(scaledContext);

return scaledInflater.inflate(R.layout.fragment_layout, container, false);
}

关于Android 用户界面规模,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42898179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com