Home » Android » dynamic – Android – Dynamically add an image view to a ScrollView

dynamic – Android – Dynamically add an image view to a ScrollView

Posted by: admin June 15, 2020 Leave a comment

Questions:

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

How to&Answers:

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>

Answer:

Look into using SurfaceView.

You will have a canvas object to draw your images on, and then aligning the coins is just a matter of mapping your pixels appropriately.

This is a good tutorial:
http://www.mindfiresolutions.com/Using-Surface-View-for-Android-1659.php

Answer:

Use a GridView instead and customize your own adapters. Gridview works like ListView