如何以编程方式确定我的Android应用程序使用的XML布局?

Ken*_*nny 9 android android-layout

如何以编程方式确定我的应用当前使用的布局(布局正常,布局大等)?我看到了getWindowManager().getDefaultDisplay().getMetrics(metrics)调用,但它似乎只处理屏幕密度,但不一定是应用程序使用的布局.我需要这些信息,因为我需要以编程方式在运行时动态地更改视图的某些定位.

提前致谢.

小智 32

一种非常简单的方法是将id和标记设置为父布局,并且在你的onCreate(),你可以findViewById()getTag().

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/my_activity_view"
    android:tag="big_screen" >
        // misc views~
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

然后,在你的onCreate方法中,

if(findViewById(R.id.my_activity_view).getTag().equals("big_screen")) {
    // do stuff
}
Run Code Online (Sandbox Code Playgroud)


And*_*nce 21

我有同样的问题.如果你正在使用layout/ layout-sw600dp/ layout-sw720dp,以下内容结束了我的工作:

Configuration config = activity.getResources().getConfiguration();

if (config.smallestScreenWidthDp >= 720) {
  // sw720dp code goes here
}
else if (config.smallestScreenWidthDp >= 600) {
  // sw600dp code goes here
}
else {
  // fall-back code goes here
}
Run Code Online (Sandbox Code Playgroud)


Yus*_*f X 0

ViewGroup view = (ViewGroup)getWindow().getDecorView();
LinearLayout content = (LinearLayout)view.getChildAt(0);
int id = content.getId();
Run Code Online (Sandbox Code Playgroud)

id 告诉您正在使用哪种布局(假设您在 XML 中设置了 id 标记)。