Search code examples
androidimagebuttononclicklistenerdisplay

Add images to screen programmatically


In one of the activity of my app, I have a button where I want to display an image with each button click. For example:

enter image description here

By clicking the button of my activity, an image appears on screen as shown.

enter image description here

The second and following clicks on the button will results in the new image to append accordingly.

enter image description here

I would like to have some suggestion on how do I achieve this.


Solution

  • I made something similar to this but with TextView. Basically I did this:

    XML:

    For my case I made TableLayout Ex:

    <TableLayout
        android:id="@+id/existedTableLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/margin_standard">
    
        <TableRow>
            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/number_text"
                android:textAppearance="@android:style/TextAppearance.DeviceDefault.Large" />
        </TableRow>
    </TableLayout>
    


    Activity

    Note: Change it to ImageView for your case

    /* //Get the TableLayout. Ex:
        private TableLayout existedTableLayout = findViewById(R.id.existedTableLayout);
    */
    /* Make onClickListerner to call below function */
    private void addTableRowDynamically() {
            //Make new Row
            TableRow newRow= new TableRow(this);
    
            TextView newNoTextView = new TextView(this);
            //some TextView method, do your research about ImageView
            newNoTextView.setLayoutParams(new TableRow.LayoutParams(0,ViewGroup.LayoutParams.WRAP_CONTENT, 1));
            newNoTextView.setText("this is text");
            newNoTextView.setTextAppearance(this, android.R.style.TextAppearance_DeviceDefault_Large);
    
            // Add the TextView to the newRow
            newRow.addView(newNoTextView);
    
            // Add the newRow which contain the TextView to the TableLayout, below
            existedTableLayout.addView(newRow, existedTableLayout.getChildCount());
    }