gpt4 book ai didi

Android - getHeight() 和 getWidth()

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

我正在 relativeLayout 中动态创建一些 ImageView,但我需要根据屏幕的高度和宽度改变大小。在我设置高度时,尚未创建 View 和布局,这意味着 getHeight()getWidth() 返回 0。我查看了其他线程在 StackOverflow 上,但似乎没有一个足够具体地解决我的问题。

我正在一个 fragment 中完成所有这些工作,如果能提供有关如何解决此问题的任何指导,我将不胜感激。她是我的一小段代码。

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_hello_moon, parent, false);

RelativeLayout rl = (RelativeLayout) v.findViewById(R.id.l1);
tl.setBackgroundColor(Color.RED);

ArrayList<ImageView> imgViews = new ArrayList<ImageView>();

//Cant get height or width of parent as hasnt been created yet
int numberOfBells = 16;
int height = rl.getHeight() / numberOfBells;
int width = rl.getWidth() / 2;

final ImageView imageTopL = new ImageView(getActivity());

if (true){
imageTopL.setId(1);
imageTopL.setImageResource(R.drawable.bell_dl_256);

RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);

params1.addRule(RelativeLayout.ALIGN_PARENT_TOP);
params1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params1.setMargins(50,10,0,10);

imageTopL.setLayoutParams(params1);

//Need the size to vary depending on the height/width
imageTopL.getLayoutParams().height = height;
imageTopL.getLayoutParams().width = width;

imageTopL.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
imageTopL.setImageResource(R.drawable.bell_ul_256);
}
});

imgViews.add(imageTopL);
}
for(ImageView i : imgViews){
rl.addView(i);
}

return v;
}

最佳答案

要获取屏幕的大小,您可以尝试:

 DisplayMetrics metrics = this.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;

看这个:Get screen dimensions in pixels

关于Android - getHeight() 和 getWidth(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19639691/

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