2014-12-04 149 views
1

我試圖以編程方式設置LayoutParams.BELOW。在這裏我的代碼:以編程方式設置LayoutParams.BELOW

RelativeLayout layout = new RelativeLayout(this.getActivity()); 
    layout.setLayoutParams(new RelativeLayout.LayoutParams(
      LayoutParams.FILL_PARENT, 
      LayoutParams.FILL_PARENT)); 
    layout.setBackgroundColor(Color.parseColor("#CCCDCDCD")); 

    ImageView imageView = new ImageView(this.getActivity()); 
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 
    params.addRule(RelativeLayout.CENTER_IN_PARENT); 
    imageView.setLayoutParams(params); 
    imageView.setBackgroundResource(R.drawable.create_template); 

    AnimationDrawable frameAnimation = (AnimationDrawable) imageView.getBackground(); 

    if (frameAnimation != null) { 
     frameAnimation.start(); 
    } 

    TextView textView = new TextView(this.getActivity()); 
    params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 
    params.addRule(RelativeLayout.BELOW, imageView.getId()); 
    textView.setLayoutParams(params); 
    textView.setText("Generating information..."); 

    layout.addView(imageView); 
    layout.addView(textView); 

    return layout; 

但它沒有正確定位。任何想法爲什麼它沒有很好的定位?

+0

你貼錯代碼。沒有「下方」可以看到,只是「上方」。你的imageview有一個ID? – ElDuderino 2014-12-04 15:41:26

+0

對不起,即使在下面或上面都不起作用... – Sonhja 2014-12-04 15:54:22

回答

4

ImageView沒有ID。你需要給它一個。無論是定義一些常量整數值,或使用View.generateViewId(),並在佈局PARAMS使用它之前調用setId()

ImageView imageView = new ImageView(this.getActivity()); 
imageView.setId(View.generateViewId()); 
... 
params.addRule(RelativeLayout.BELOW, imageView.getId()); 
+0

這對我來說非常合適! – Sonhja 2014-12-04 15:56:02