Create and validate check box programmatically using Java in Android - android

I need to create a number of check boxes programmatically using Java, check if one of them is checked and when I click Next Button the control will move to next page. If none of them is checked a toast message has to be displayed. Please suggest as I am new to Android.
Here is my code:
public class TestValidCheckboxActivity extends Activity implements OnCheckedChangeListener{
private RelativeLayout layoutMiddle = null;
private TableLayout layout1;
private CheckBox chk;
private String[] resarr = {"silu", "pinky", "meera"};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
layoutMiddle = (RelativeLayout)findViewById(R.id.layoutMiddleUp);
layout1 = (TableLayout)findViewById(R.id.tableId1);
final Button btnNext = (Button)findViewById(R.id.btnNext);
int i = 0;
for(String res: resarr){
TableRow tr=new TableRow(this);
chk=new CheckBox(this);
chk.setId(i);
chk.setText(res);
chk.setTextColor(Color.BLACK);
tr.addView(chk);
i++;
RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
lay.addRule(RelativeLayout.BELOW, layoutMiddle.getId());
layout1.addView(tr, lay);
}
chk.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
if (arg1)
{
btnNext.setOnClickListener(new View.OnClickListener() {
public void onClick(final View view) {
Log.e("1111111111","111111111");
if(chk.isChecked()){
Intent intent = new Intent(view.getContext(),NextPage.class);
startActivityForResult(intent, 0);
}else{
Toast msg = Toast.makeText(view.getContext(), "please choose at least one option", Toast.LENGTH_LONG);
msg.show();
}
}
});
}else{
Toast msg = Toast.makeText(TestValidCheckboxActivity.this, "please choose at least one option", Toast.LENGTH_LONG);
}
}
});
}
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
}
}

this can be easily done
take a boolean flag and set true it on checkbox.isChecked();(inbuilt)
then check if flag is set then navigate to next else TOAST

Can you show us some of your layout code, meaning, are the checkboxes defined in an xml file and do they have IDs?
If they do, you can access each of them with findViewByID and check their status one by one.

Related

get OnClick() from programmatically added buttons?

i have added some button in a layout:
LinearLayout row = (LinearLayout)findViewById(R.id.KeysList);
keys=db.getKeys(console);
my_button=new Button[keys.size()];
for (bt=0;bt<keys.size();bt++){
my_button[bt]=new Button(this);
my_button[bt].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.FILL_PARENT));
my_button[bt].setText(keys.get(bt));
my_button[bt].setId(bt);
row.addView(my_button[bt]);
my_button[bt].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (my_button[bt].getId() == ((Button) v).getId()){
Toast.makeText(getBaseContext(), keys.get(bt), 0).show();
}
}
});
}
I want to know which button is clicked and how to get text of the clicked button?And I think using bt here dose not seem to work!
This code is running. I hope it help you :)
final ArrayList<String> Keys = new ArrayList<String>();
for(int i = 0; i < 10; i ++){
Keys.add("Keys is : " + String.valueOf(i));
}
LinearLayout Row = (LinearLayout)findViewById(R.id.KeysList);
final Button[] my_button = new Button[Keys.size()];
for (int bt = 0; bt < Keys.size(); bt ++){
final int Index = bt;
my_button[Index] = new Button(this);
my_button[Index].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
my_button[Index].setText(Keys.get(Index));
my_button[Index].setId(Index);
my_button[bt].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (my_button[Index].getId() == ((Button) v).getId()){
Toast.makeText(getBaseContext(), Keys.get(Index), 0).show();
}
}
});
Row.addView(my_button[Index]);
}
ExampleProject id : Your project
You should probably use View#setTag to set some arbitrary data you'd like associate with the Button. Then you can just instantiate only one OnClickListener that then uses getTag and acts on that data in whatever way you need.
Another way is to have your Activity listen to all button clicks and then you just filter respective to the ID. You should not get the text of the button and use that at all. You should use your own type of identifier, ideally the idea should be enough. Or perhaps you use setTag as #qberticus described.
Consider This example :
public class MainActivity extends Activity implements View.OnClickListener
{
LinearLayout linearLayout;
Button [] button;
View.OnClickListener listener;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout=(LinearLayout)findViewById(R.id.parent_lay);
String[] array={"U123","U124","U125"};
int length=array.length;
System.out.println("11111111111111111111111111");
button=new Button[length];
for(int i=0;i<length;i++)
{
button[i]=new Button(getApplicationContext());
button[i].setId(i);
button[i].setText("User" + i);
button[i].setOnClickListener(this);
linearLayout.addView(button[i]);
}
}
#Override
public void onClick(View view)
{
view.getId();
Button button=(Button)findViewById(view.getId());
button.setText("Changed");
}
}
This works fine :)

When creating a button from a Dialog Box

The original code has been deleted, the new working code is shown. The idea behind the code is to create a new textView within a layout that has a custom name to it that the user provides. Previously, a NPE error was happening. This is a fix. Any questions, please feel free to ask.
EDIT: Found the solution
The fix needs to be as followed:
accountEdit = new EditText(this); // accountEdit needs to be a global variable
then within the builder.setPositiveButton
builder.setPositiveButton(R.string.btn_save, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dInterface, int whichButton)
{
LinearLayout lineLayout = (LinearLayout)findViewById(R.id.linear_layout);
String newAccountName = accountEdit.getText().toString();
newTextView = new TextView( getBaseContext() );
newTextView.setVisibility(View.VISIBLE);
newTextView.setText( newAccountName );
newTextView.setId(id);
newTextView.setTextSize(35);
newTextView.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickNew(view);
}
});
newTextView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
Toast.makeText(getBaseContext(), "Testing" , Toast.LENGTH_LONG).show();
return true;
}
});
This will create the button, as well as set the name of the button to the information that is in the EditText within the Dialog Box. Previously, the EditText was from another activity, and was being called wrong, which caused the NPE. Thank you for all the help.
As Wenhui metioned, you call the finViewById inside the onclick listener of the button, so the wrong context is used. Do it like in the following example:
final EditText accountEdit = (EditText)findViewById(R.id.newAccountButton);
final String newAccountName = accountEdit.getText().toString();
final LinearLayout lineLayout = (LinearLayout)findViewById(R.id.linear_layout);
builder.setPositiveButton(R.string.btn_save, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dInterface, int whichButton)
{
newTextView = new TextView(getBaseContext());
newTextView.setVisibility(View.VISIBLE);
newTextView.setText("Test");
newTextView.setId(id);
newTextView.setTextSize(35);
newTextView.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickNew(view);
}
});
lineLayout.addView(newTextView);
id++;
}
});

show/hide an listView on a buttonClick

final ImageView patientAllergyImage = (ImageView) findViewById(R.id.image);
patientAllergyImage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
patientAllergyImage.setImageDrawable(getResources().
getDrawable(R.drawable.nav_down_green));
List.setVisibility(View.GONE);
}
});
I am making my List to Hide, but how do i show it when i click on the same button. I am not able to keep a boolean to check whether its clicked or not as it saying... The final local variable clicked cannot be assigned, since it is defined in an enclosing type neither an non final variable
Try this,
public void onClick(View V){
patientAllergyImage.setImageDrawable(getResources().
getDrawable(R.drawable.nav_down_green));
List.setVisibility(List.isShown() ? View.GONE : View.VISIBLE);
}
Instead of typical button, you can use a toogle Button to achieve this
ToggleButton toggle = (ToggleButton) findViewById(R.id.togglebutton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// hide the listview
} else {
// show the listview
}
}
});
Try something like this:
public void onClick(View v) {
// TODO Auto-generated method stub
patientAllergyImage.setImageDrawable(getResources().
getDrawable(R.drawable.nav_down_green));
if(List.getVisibility()==View.VISIBLE){
List.setVisibility(View.INVISIBLE)
}else{
List.setVisibility(View.VISIBLE)
}
}
Replace INVISIBLE by GONE if needed. Hope this helped.
Remove final for boolean variable or
try this
try this
if(List.getVisibility()==View.GONE)
{
List.setVisibility(View.VISIBLE);
}
if(List.getVisibility()==View.VISIBLE)
{
List.setVisibility(View.GONE);
}
Seems that there are a few issues here.
First of all you shouldn't call your listview "List" this is masking the real class called List.
Best to use "listView" with a lowercase "l" if you are stuck for a decent variable name.
You don't need to use final everywhere.
Use setImageResource instead to keep you code clean and readable.
Use the ?true:false syntax when it is readable
ImageView patientAllergyImage = (ImageView) findViewById(R.id.image);
patientAllergyImage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//see if the list view is visible
bool bVisible = listView.getVisibility();
//select the image resource
int iImageRes = bVisible?R.drawable.nav_down_green:R.drawable.nav_up_green;
//Toggle Image
(ImageView)v.setImageResource(iImageRes);
//Toggle List Visibility
listView.setVisibility(bVisible?View.GONE:View.VISIBLE);
}
});

Drag and drop images in gridview in android

I'am developing a sample android application to learn about drag & drop in android. On start of the app, i'am displaying few images on a grid view. Now i need to drag one image at a time over to the place of another. After dropping an image over another, the images should swap its places. How can i achieve it ? Please guide/help me.
You can easily achieve this by using thquinn's DraggableGridView
You can add your custom layout
public class DraggableGridViewSampleActivity extends Activity {
static Random random = new Random();
static String[] words = "the of and a to in is be that was he for it with as his I on have at by not they this had are but from or she an which you one we all were her would there their will when who him been has more if no out do so can what up said about other into than its time only could new them man some these then two first may any like now my such make over our even most me state after also made many did must before back see through way where get much go well your know should down work year because come people just say each those take day good how long Mr own too little use US very great still men here life both between old under last never place same another think house while high right might came off find states since used give against three himself look few general hand school part small American home during number again Mrs around thought went without however govern don't does got public United point end become head once course fact upon need system set every war put form water took".split(" ");
DraggableGridView dgv;
Button button1, button2;
ArrayList<String> poem = new ArrayList<String>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dgv = ((DraggableGridView)findViewById(R.id.vgv));
button1 = ((Button)findViewById(R.id.button1));
button2 = ((Button)findViewById(R.id.button2));
setListeners();
}
private void setListeners()
{
dgv.setOnRearrangeListener(new OnRearrangeListener() {
public void onRearrange(int oldIndex, int newIndex) {
String word = poem.remove(oldIndex);
if (oldIndex < newIndex)
poem.add(newIndex, word);
else
poem.add(newIndex, word);
}
});
dgv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
Toast.makeText(getApplicationContext(), "On clicked" +position, Toast.LENGTH_SHORT).show();
dgv.removeViewAt(position);
poem.remove(position);
}
});
button1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
String word = words[random.nextInt(words.length)];
addView();
poem.add(word);
}
});
button2.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
String finishedPoem = "";
for (String s : poem)
finishedPoem += s + " ";
new AlertDialog.Builder(DraggableGridViewSampleActivity.this)
.setTitle("Here's your poem!")
.setMessage(finishedPoem).show();
}
});
}
public void addView()
{
LayoutParams mLayoutParams= new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
LinearLayout mLinearLayout= new LinearLayout(DraggableGridViewSampleActivity.this);
mLinearLayout.setOrientation(LinearLayout.VERTICAL);
mLinearLayout.setGravity(Gravity.CENTER_HORIZONTAL);
ImageView mImageView = new ImageView(DraggableGridViewSampleActivity.this);
if(dgv.getChildCount()%2==0)
mImageView.setImageResource(R.drawable.child1);
else
mImageView.setImageResource(R.drawable.child2);
mImageView.setScaleType(ImageView.ScaleType.FIT_XY);
mImageView.setLayoutParams(mLayoutParams);
mImageView.setId(dgv.getChildCount());
mImageView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), v.getId()+"clicked ", Toast.LENGTH_SHORT).show();
return dgv.onTouch(v, event);
}
});
TextView mTextView = new TextView(DraggableGridViewSampleActivity.this);
mTextView.setLayoutParams(mLayoutParams);
mTextView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), v.getId()+"clicked text ", Toast.LENGTH_SHORT).show();
return dgv.onTouch(v, event);
}
});
TextView mTextViewLabel = new TextView(DraggableGridViewSampleActivity.this);
mTextViewLabel.setText(((dgv.getChildCount()+1)+""));
mTextViewLabel.setLayoutParams(mLayoutParams);
mTextViewLabel.setId(dgv.getChildCount());
mTextViewLabel.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Toast.makeText(getApplicationContext(), v.getId()+"clicked text ", Toast.LENGTH_SHORT).show();
return dgv.onTouch(v, event);
}
});
mLinearLayout.setTag(mTextViewLabel);
mLinearLayout.addView(mTextViewLabel);
mLinearLayout.addView(mImageView);
mLinearLayout.addView(mTextView);
dgv.addView(mLinearLayout);
}
}

Using a button and then showing dynamic text

I am writing a program that when the user enter a number text appears according to that number. My problem is that the button line has public void ... after this I am trying to use if statements and return methods, but because of the public void, the return method can not return anything. I tried to close the public void, but I am getting errors. Please help.
The code is as follows. I have included the different codes that I have tried like toast, etc..
ente#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.go);
button.setOnClickListener(mAddListener);
// tv = (TextView) findViewById(R.id.textView1);
}
private OnClickListener mAddListener = new OnClickListener()
{
public void onClick(View v) {
}}
;
//Toast.makeText(Num.this, "This Display", Toast.LENGTH_SHORT).show();
//toast.show();
//finish ();
// long id = 0;
// try
{
PleaseEnter=(EditText)findViewById(R.id.PleaseEnter);
{
}
if (PleaseEnter.equals("1"))
// tv.setText("This is the display 1.");
return "This display";
// Context context = getApplicationContext();
// CharSequence text ="this display";
// int duration =Toast.LENGTH_LONG;
// Toast toast =Toast.makeText(context, text, duration);
// toast.show();
else if (PleaseEnter.equals("2"))
return;
//tv.setText("Dispaly 2");
You can define your own method at Activity level, such as:
private void onTextEdited(String content) {
// deal with the String
}
In the onClick method of your OnClickListener, you can call it such as:
public void onClick(View v) {
EditText myEditText = (EditText) findViewById(R.id.PleaseEnter);
onTextEdited(myEditText.getText().toString());
}

Categories

Resources