如何动态设置图像大小和位置
问题描述:
我想启动图像的边距和大小.i在xml中有代码,我想动态地编写它。我已经阅读了Stackoverlow中给出的所有答案但是我无法了解it.Kindly帮我out.I附上以下如何动态设置图像大小和位置
<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代码对于这个XML我想它写在Java代码。
答
试试这个:
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
+0
他* * layout_toRightOf' *显然他没有使用'LinearLayout'作为父布局 – Selvin
答
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()
);
*但我不明白*为什么你认为你能够理解另一个答案吗? – Selvin
我dono如何动态地编写代码,我喜欢学习。学习新事物是错误的。 –
@Selvin,你应该已经知道了,*我无法理解它* ==请提供代码我可以复制粘贴,我不知道我在做什么...... – 2Dee