4

是否可以在启动任何活动之前获得设备纵横比?

我正在尝试根据我的设备被标识为“long”还是“not_long”来设置宽度。这应该在活动启动之前很久就可用,但我不确定在哪里可以获得这个变量。执行此方法时,活动不可用。另外,为了避免内存泄漏,我不想将活动传递给包含以下方法的类。

这是失败的调用方法:

public int getDefaultWidth() { 
        Configuration myConfig = new Configuration();
        myConfig.setToDefaults();
        myConfig = getResources().getConfiguration();

        switch (myConfig.screenLayout & Configuration.SCREENLAYOUT_LONG_MASK) {

            case Configuration.SCREENLAYOUT_LONG_NO: {
                return this._defaultWidth;
            }
            case Configuration.SCREENLAYOUT_LONG_YES: {
                return this._defaultWidthLong;
            }
            case Configuration.SCREENLAYOUT_LONG_UNDEFINED: {
                return this._defaultWidth;
            }
        }
        return this._defaultWidth;
    }
4

3 回答 3

0

这是在哪里执行的?我看不到您如何执行代码并且没有从 Context 继承的实例化的东西。Service 继承自 Context,BroadcastReceiver 的 onReceive 被赋予一个 Context。

此外,您可以从调用此方法的位置传入一个配置对象,而不是传入一个上下文。

于 2011-06-21T20:47:03.623 回答
0

当您从活动中调用此方法时。您可以将“this”作为 getDefaultWidth() 方法的参数传递。然后,您可以将其用作上下文。

public int getDefaultWidth(Context context) { ... }

并在活动中称其为

int width = getDefaultWidth(this)
于 2011-06-21T20:57:08.703 回答
0

您的应用程序的应用程序上下文是在任何活动之前创建的。应用程序具有有效的上下文,因此您可以使用它来获取所需的任何内容,设置静态或成员变量,然后在您的第一个活动中引用它。

可以通过添加一个扩展 Application 的新类并在 AndroidManifest.xml 中进行小的更改来处理应用程序上下文

显现:

<application android:enabled="true"...
   android:name=".Foo">
...
</application>

将新类添加到扩展 Application 的项目中:

public class Foo extends Application {

private int mWidth;

@Override
public void onCreate() {
    super.onCreate();
    // do stuff to set mWidth using the Application context like:
    // mWidth = getResources().getConfiguration().blahblahblah
}   

public int getWidth() {
    return mWidth;
}

从您的活动中,只需执行以下操作即可获得宽度:

int width = ((Foo)getApplication()).getWidth();
于 2011-06-21T21:09:41.627 回答