Reputation: 163
Allow me to explain. I have :
a button with picture (located at @drawable/pic),
linear layout (id=linear1)
the button xml is below :
<ImageButton
android:id="@+id/imageButton1"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_marginRight="10dp"
android:scaleType="fitXY"
android:src="@drawable/pic"
android:maxWidth="80dp"
android:maxHeight="80dp"
tools:ignore="ContentDescription" />
the linear layout xml is as follow :
<LinearLayout
android:id="@+id/layout1"
android:layout_width="match_parent"
android:layout_height="80dp"
android:gravity="center"
android:orientation="horizontal"
tools:ignore="UselessLeaf" >
what i want is, when i click the button i want to create/generate imageview programatically inside the linearlayout and i want to fill it with the same picture for the button (pic). The code is below :
//initiate imageview
ImageView img=new ImageView(this);
//get drawable from button
Drawable blabla=btn1.getDrawable();
//set drawable to imageview
img.setImageDrawable(blabla);
//set height and width of imageview to 50dp
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(50,50);
img.setLayoutParams(parms);
img.setScaleType(ScaleType.FIT_XY);
//place imageview to linearlayout
layoutTempat.addView(img);
The code works fine with displaying the imageview with the same image as the button have. however the problem is : when i set the imageview to 50dp programatically, the image inside button changed too.. how can it happened ? i am so confused as iam a newbie..
Thanks before.
Upvotes: 0
Views: 1804
Reputation: 10177
The two views are sharing the same drawable.
It's plausible your manipulations on one view are being sent to the underlying drawable, effecting how its displayed in the other view -- frankly I don't know. But assuming the case is as you described, this problem is easily fixed by cloning the drawable as follows:
Drawable dr = btn1.getDrawable().getConstantState().newDrawable();
img.setImageDrawable(dr);
Upvotes: 3