2

我在一個relativeLayout中動態創建一些ImageViews,但我需要的大小取決於屏幕的高度和寬度。在我設置高度時,視圖和佈局沒有被創建,這意味着getHeight()getWidth()返回0.我已經看過StackOverflow上的其他線程,但沒有一個看起來足以滿足我的問題。Android-getHeight()和getWidth()

我在片段中做了所有這些,希望能得到關於如何解決這個問題的任何指導。她是我的代碼的一小部分。

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

回答

1

得到屏幕的大小,你可以嘗試:

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

看看這個:Get screen dimensions in pixels

0

您正試圖獲得的意見的大小,他們實際上是測量和佈置前(在onCreateView返回之前)。僅僅因爲你誇大了觀點並不意味着系統對尺寸有任何想法。嘗試計算onCreateView在onActivityCreated中返回後的大小。

0

您可以使用

getViewTreeObserver().addOnPreDrawListener(new OnPreDarwListener() { 
    .... run() { 
    getHeight() + getWidth related stuff. 
    getViewTreeObserver.removeOnPreDrawListener(this); 
    } 
}); 
0

要查找的高度和屏幕的寬度得到高度和寬度,你可以試試這個:

DisplayMetrics metrics = new DisplayMetrics(); //for all android versions 
getWindowManager().getDefaultDisplay().getMetrics(metrics); 
int Measuredwidth = metrics.widthPixels;  
int Measuredheight = metrics.heightPixels; 
相關問題