Android - Dynamically add an image view to a ScrollView
39,831
Try this sample
MainActivity
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_main);
LinearLayout linearLayout1 = (LinearLayout) findViewById(R.id.linearLayout1);
for(int x=0;x<3;x++) {
ImageView image = new ImageView(MainActivity.this);
image.setBackgroundResource(R.drawable.ic_launcher);
linearLayout1.addView(image);
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<ScrollView
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</LinearLayout>
</ScrollView>
</LinearLayout>
Author by
Shmuel
Updated on August 15, 2022Comments
-
Shmuel almost 2 years
I'm pretty new to Android and need a bit of help with some code.
Basically I have an array of coins and I want to dynamically display images for the coins in a ScrollView. Each time the user adds a coin the view should update appropriately.
Thank you!
Here is a screenshot of what I want to do - http://i.imgur.com/3l2fxKw.png
-
Shmuel over 11 yearsyah. thanks. this is what i have now -i.imgur.com/eRzN3Sb.png (the color is just for debugging purposes.) one last thing, i want to be able to load the appropriate image from the array for each coin. basically i want to be able to say coinView.setBackgroundResource(coinArray[x].image) i assume i need to somehow use a drawable object and i was hoping its possible to include it in my enum class. the enum class looks like
code
(test) -
Shmuel over 11 yearsI ran out of space in the comment above. I still need some help using drawables in my enum class. this is the link to my new question stackoverflow.com/questions/15182045/… thank you
-
Anitha about 9 years"attempt to invoke virtual method on a null object reference" any idea why?