Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add New View to Layout Upon Button Click in Android

Tags:

android

view

I'm developing a Scorekeeping Application for the card game "Spades".

Upon a button click at the end of each hand, I would like to store some information about the hand into a TextView and display all of the hand histories in a ScrollView.

How can I modify an .XML layout or otherwise add a new TextView to a layout in code?

I have tried...

public static LinearLayout gamehistory;

gamehistory = (LinearLayout) findViewById(R.id.gamehistory);


public void setClickListener1(){

lockwagersButton.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {

setContentView(R.layout.results_layout);

gameHistory.addView(new TextView(...));       //  I can't get this to work 
            ...

Thanks! -K.H.

like image 972
K. H. Avatar asked Jan 27 '26 03:01

K. H.


1 Answers

following code add textview onclick:

public class ViewOnClick extends Activity {
    LinearLayout.LayoutParams layoutParams;
    LinearLayout ll;
    static int i;

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

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button b = (Button)findViewById(R.id.Button01);
        ll = (LinearLayout)findViewById(R.id.ll);
        layoutParams = new LinearLayout.LayoutParams
        (LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        b.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                TextView view = new TextView(ViewOnClick.this);             
                view.setText(++i+" view");
                ll.addView(view, layoutParams); 

            }
        });
    }
}
like image 174
Vivek Avatar answered Jan 31 '26 05:01

Vivek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!