Showing posts with label ddynamically generate the button. Show all posts
Showing posts with label ddynamically generate the button. Show all posts

Sunday, 15 September 2013

dynamically generate the button using android native



Dynamically generate the button using Button Click Event





MainActivity:


package com.example.dynamiccreation;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;

public class MainActivity extends Activity {
    Context context;
    ScrollView scrollView;
    LinearLayout container;
    LinearLayout layout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        setContentView(R.layout.activity_main);
         layout = (LinearLayout) findViewById(R.id.LinearAdd);


    }

    public void addButton(View view) {
        Button button  = new Button(MainActivity.this);
        LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT );
        button.setLayoutParams(lp);
        button.setText("ADDED");
        layout.addView(button);
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

   
}




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" >

    <LinearLayout
        android:id="@+id/LinearAdd"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="70"
        android:orientation="vertical" >

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="addButton"
            android:text="click to add" />
    </LinearLayout>

</LinearLayout>





Result :