Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add images to a LinearLayout programmatically?

There is a LinearLayout and some Buttons in my project. I want when each Button clicked add a small image to LinearLayout from drawable. How can I add a image to a LinearLayout programmatically?

This is my LinearLayout in a HorizontalScrollView:

     <HorizontalScrollView
        android:id="@+id/horizontalScrollView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top|center"
        >

        <LinearLayout
            android:id="@+id/LinearLayout1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >


        </LinearLayout>
    </HorizontalScrollView>

and here is my activity:

public class MainActivity extends Activity
{

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

            final LinearLayout notes = (LinearLayout)  findViewById(R.id.LinearLayout_notes);
            final  ImageView notes_do = new ImageView(this);
            notes_do.setBackgroundResource(R.drawable.notes_do);

    new Thread(new Runnable() {
        @Override
        public void run() {

    final ImageButton img_1 = (ImageButton) findViewById(R.id.img_1_);
    img_1.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

        if( event.getAction() ==  MotionEvent.ACTION_DOWN ) {

              notes.addView(notes_do);

        }
            return true;
        } 

       });  // end of ontouch

           }
          }).start(); // end of thread      


} // end of oncreate
}// end of activity
like image 543
Mahdi Jafarzadeh Avatar asked Jan 29 '13 12:01

Mahdi Jafarzadeh


1 Answers

    LinearLayout ll = (LinearLayout)findViewById(R.id.LinearLayout1);
for(int i=0;i<5;i++)
{
        ImageView ii= new ImageView(this);
        ii.setBackgroundResource(R.drawable.ic_action_search);
        ll.addView(ii);
}
like image 74
Pinki Avatar answered Sep 20 '22 21:09

Pinki