问题在主要活动中显示图像

时间:2017-02-26 06:19:15

标签: android imageview

我正在尝试以编程方式在主要活动上显示图像。我以前在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);   

2 个答案:

答案 0 :(得分:1)

在活动中,我们通过调用setContentView(R.layout.activity_main);

在活动的onCreate方法中为视图充气

如果您想以编程方式向此视图添加图片,请先尝试获取活动的根视图:

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

答案 1 :(得分:1)

您需要设置其高度宽度:

\Carbon\Carbon::now()->addDays(30);