我正在以编程方式创建我的视图,根本没有 xml,需要我正在工作的区域的实际大小。我一直在使用这段代码:
public static class DummySectionFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (container == null) {
return null;
}
Context context = getActivity();
int tabNo = getArguments().getInt(ARG_SECTION_NUMBER);
Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
// check display size to figure out what image resolution will be loaded
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
Point size = new Point();
display.getRealSize(size);
display.getSize(size);
int width = size.x;
int height = size.y;
但这并没有考虑到标题栏和导航栏等所有其他“装饰”
文档说不要使用显示指标来获取大小,但我怎样才能在 onCreateView 中找出视图的大小?我试过 container.getHeight() 但返回 0
我想问题是视图尚未创建,但必须有一个 onCreateView 的父级知道视图有多大是对的?
我怎么找到那个?
谢谢
仅供参考,这有效:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (container == null) {
return null;
}
Context context = getActivity();
int tabNo = getArguments().getInt(ARG_SECTION_NUMBER);
Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
// check display size to figure out what image resolution will be loaded
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
Point size = new Point();
display.getRealSize(size);
display.getSize(size);
int width = size.x;
int height = size.y;
switch (metrics.densityDpi) {
case DisplayMetrics.DENSITY_XXHIGH: height -= 72; break;
case DisplayMetrics.DENSITY_XHIGH: height -= 64; break;
case DisplayMetrics.DENSITY_HIGH: height -= 48; break;
case DisplayMetrics.DENSITY_MEDIUM: height -= 32; break;
case DisplayMetrics.DENSITY_LOW: height -= 24; break;
default:
Log.e("onCreateView", "Unknown density");
}
}
但这似乎不是一种干净的方法。我猜到了 xhigh 和 xxhigh,我还没有找到实际数字
另外我应该补充一点,视图是从 MainActivity 中的 onTabSelected 创建的,如下所示
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, show the tab contents in the
// container view.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, tab.getPosition() + 1);
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();
}