2017-02-26 69 views
-1

我試圖以編程方式在主要活動上顯示圖像。我之前在ContentFragment上成功完成了這個任務,但由於某種原因,在成功構建之後,圖像不存在。在主要活動中顯示圖像問題

我的示例代碼:

LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    View myView = inflater.inflate(R.layout.activity_main, null); 
    ViewGroup mainLayout = (RelativeLayout) myView; 

    ImageView wView = new ImageView(this); 
    Drawable W = ContextCompat.getDrawable(this, R.drawable.w); 

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

    wView.setImageDrawable(W);       
    imageParam.setMargins(100, 100, 0, 0); 
    mainLayout.addView(wView); 
    wView.setLayoutParams(imageParam); 

回答

0

在活動,我們通過調用膨脹在活動的onCreate方法的觀點:setContentView(R.layout.activity_main);

如果你想圖像添加到這個視圖編程嘗試獲得活動的根查看第一:

ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0); 

然後將圖片上傳到這樣的觀點:

public class MainActivity extends AppCompatActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0); 

     ImageView wView = new ImageView(this); 
     Drawable W = ContextCompat.getDrawable(this, R.drawable.w); 

     RelativeLayout.LayoutParams imageParam = new RelativeLayout.LayoutParams(
       RelativeLayout.LayoutParams.WRAP_CONTENT, 
       RelativeLayout.LayoutParams.WRAP_CONTENT); 
     imageParam.setMargins(100, 100, 0, 0); 
     wView.setLayoutParams(imageParam); 
     wView.setImageDrawable(W); 
     viewGroup.addView(wView); 
    } 
} 
+0

非常感謝,這個工作正是我怎麼想。另外我喜歡你如何堆疊RelativeLayout初始化。這看起來很整齊。 –

1

您需要設置它的高度寬度:

ImageView wView = new ImageView(this); 
((ViewGroup.LayoutParams)(wView.getLayoutParams())).width = 200; 
((ViewGroup.LayoutParams)(wView.getLayoutParams())).height = 200; 
+1

感謝您回覆我的問題,但我擔心沒有得到顯示的圖像。 CookieMonster的實現工作,但我很高興你分享你的代碼,因爲我需要稍後調整高度和寬度參數。 –