Android-getHeight()和getWidth() [英] Android - getHeight() and getWidth()

查看:118
本文介绍了Android-getHeight()和getWidth()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要在relativeLayout中动态创建一些ImageView,但是我需要根据屏幕的高度和宽度来改变大小.在设置高度的点上,还没有创建视图和布局,这意味着getHeight()getWidth()返回0.我看过StackOverflow上的其他线程,但似乎都还不足以解决我的问题.

I am dynamically creating some ImageViews inside a relativeLayout but I need the size to vary depending on the height and width of the screen. At the point where I set the height the views and layouts havent been created which means that the getHeight() and getWidth() are returning 0. I have looked at other threads on StackOverflow but none seem specific enough to my problem.

我正在片段中完成所有这些工作,并希望获得有关如何解决此问题的任何指导.她是我代码的一小段.

I am doing all this in a Fragment and would appreciate any guidance on how to solve this. Her is a small snippet of my code.

@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;
}

推荐答案

要获取屏幕尺寸,您可以尝试:

to get the size of the screen you can try:

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

查看以下内容:获取以像素为单位的屏幕尺寸

这篇关于Android-getHeight()和getWidth()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆