Reputation: 13
i just started to develop a simple checklist app, the idea is that i have an EditText, and a button. When i enter the text and hit the "add" button i want it to make a checklist. i have managed to get the app to display a check-box with the text i enter, the only problem is that i can't find a way to get new check-box'es onto the screen.
And the most annoying thing is that i know why it is doing this, i have declared just one checkbox named "cb", and of course when i hit enter it will always assign new values to "cb".
would be very thankful if anyone could point me in the right direction.
package com.pzayx.shoppinglist;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
public class MainActivity extends Activity {
int i = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_dynamic_views);
/*
* Adds scrollview inside a linearlayout,
*setting up a edittext, a add button and a checkbox
*/
final CheckBox cb = new CheckBox(this);
ScrollView scrl = new ScrollView(this);
final LinearLayout lil = new LinearLayout(this);
lil.setOrientation(LinearLayout.VERTICAL);
scrl.addView(lil);
final EditText EDIT_TEXT = new EditText(this);
EDIT_TEXT.setText("");
lil.addView(EDIT_TEXT);
Button btn = new Button(this);
btn.setText("Add");
lil.addView(btn);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
String text = EDIT_TEXT.getText().toString();
EDIT_TEXT.setText("");
cb.setId(i);
cb.setText(text);
text = null;
lil.addView(cb);
i++;
} catch (Exception e) {
e.printStackTrace();
}
}
});
this.setContentView(scrl);
}
public boolean OnCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Upvotes: 1
Views: 1229
Reputation: 3359
Try:
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
for(int i = 0; i < 20; i++) {
CheckBox cb = new CheckBox(getApplicationContext());
cb.setText("I'm dynamic!");
lil.addView(cb);
}
}
});
Upvotes: 2