我想要启动图像的边距和大小。我有xml中的代码,我想动态编写它。我已经阅读了Stackoverlow中给出的所有答案但是我无法理解它。请帮助我我正在附上下面的xml代码
<ImageView
android:id="@+id/coin1"
android:layout_width="20dp"
android:layout_height="20dp"
android:src="@mipmap/coin2"
android:layout_marginTop="25dp"
android:layout_toRightOf="@+id/ten_btn"
android:layout_marginLeft="35dp"
/>
对于这个Xml,我想用java代码编写它。
答案 0 :(得分:0)
试试这个:
ll_layout = (LinearLayout) findViewById(R.id.ll_layout);//parent layout of imageView
ImageView imageView = new ImageView(this);//initialize imageview
imageView.setLayoutParams(new LinearLayoutCompat.LayoutParams(100, 100));//set hight and width
//or
imageView.setLayoutParams(new LinearLayoutCompat.LayoutParams((int) getResources().getDimension(R.dimen.iv_width), (int) getResources().getDimension(R.dimen.iv_height)));
//or
imageView.setLayoutParams(new LinearLayoutCompat.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
ll_layout.addView(imageView);//add image in parent layout
答案 1 :(得分:0)
RelativeLayout root = (RelativeLayout)findViewById(R.id.your_id);
ImageView iv = new ImageView(YourActivity.this);
iv.setImageDrawable(getResources().getDrawable(R.drawable.frnd_inactive));
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(20,20);
layoutParams.addRule(RelativeLayout.RIGHT_OF,R.id.ten_btn);
layoutParams.setMargins(35, 25, 0, 0);
iv.setLayoutParams(layoutParams);
root.addView(iv);
请注意,所有值都以像素为单位。要将dp测量值转换为像素,请尝试使用
Resources r = mContext.getResources();
int px = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
yourdpmeasure,
r.getDisplayMetrics()
);