How to make boolean buttons in Android random? - android

I have four buttons and they are boolean - i want to make them different every time the image and the text inside them changes - i.e. once a button will be true, other time it will be false. How can this be done? Thank u !
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
startActivity(item.getIntent());
return true;
}
public void onNoButton(View v) {
handleAnswerAndShowNextQuestion(false);
}
public void onYesButton(View v) {
handleAnswerAndShowNextQuestion(true);
}
private void handleAnswerAndShowNextQuestion(boolean bAnswer) {
int curScore = mGameSettings.getInt(GAME_PREFERENCES_SCORE, 0);
int nextQuestionNumber = mGameSettings.getInt(GAME_PREFERENCES_CURRENT_QUESTION, 1) + 1;
Editor editor = mGameSettings.edit();
editor.putInt(GAME_PREFERENCES_CURRENT_QUESTION, nextQuestionNumber);
// Log the number of "yes" answers only
if (bAnswer == true) {
editor.putInt(GAME_PREFERENCES_SCORE, curScore + 1);
}
editor.commit();
if (mQuestions.containsKey(nextQuestionNumber) == false) {
// Load next batch
try {
loadQuestionBatch(nextQuestionNumber);
} catch (Exception e) {
Log.e(DEBUG_TAG, "Loading updated question batch failed", e);
}
}
if (mQuestions.containsKey(nextQuestionNumber) == true) {
// Update question text
TextSwitcher questionTextSwitcher = (TextSwitcher) findViewById(R.id.TextSwitcher_QuestionText);
questionTextSwitcher.setText(getQuestionText(nextQuestionNumber));
// Update question image
ImageSwitcher questionImageSwitcher = (ImageSwitcher) findViewById(R.id.ImageSwitcher_QuestionImage);
Drawable image = getQuestionImageDrawable(nextQuestionNumber);
questionImageSwitcher.setImageDrawable(image);
} else {
// Tell the user we don't have any new questions at this time
handleNoQuestions();
}
}
private void handleNoQuestions() {
TextSwitcher questionTextSwitcher = (TextSwitcher) findViewById(R.id.TextSwitcher_QuestionText);
questionTextSwitcher.setText(getResources().getText(R.string.no_questions));
ImageSwitcher questionImageSwitcher = (ImageSwitcher) findViewById(R.id.ImageSwitcher_QuestionImage);
questionImageSwitcher.setImageResource(R.drawable.noquestion);
// Disable yes button
Button yesButton = (Button) findViewById(R.id.Button_Yes);
yesButton.setEnabled(false);
// Disable no button
Button noButton = (Button) findViewById(R.id.Button_No);
noButton.setEnabled(false);
}

This is simple. Just create your environment (image and buttons) like normal. Assign your proper listeners for the buttons. Then create a new Random object. Get a random boolean. If the boolean == true, add the true button to your layout first, else add the false button.
public View getEnvironment(Context context) {
RelativeLayout rl = new RelativeLayout(context);
ImageView image = new ImageView(context);
image.setId(0);
// Instantiate image (add image and listener is needed)
Button truee = new Button(context);
// Add event listener
Button falsee = new Button(context);
// Add event listener
Random rand = new Random();
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(80, 80);
lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
image.setLayoutParams(lp);
RelativeLayout.LayoutParams left = new RelativeLayout.LayoutParams(40, 80);
lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
lp.addRule(RelativeLayout.BELOW, 0);
RelativeLayout.LayoutParams right = new RelativeLayout.LayoutParams(40, 80);
lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
lp.addRule(RelativeLayout.BELOW, 0);
if (rand.nextBoolean()) {
truee.setLayoutParams(left);
falsee.setLayoutParams(right);
} else {
truee.setLayoutParams(right);
falsee.setLayoutParams(left);
}
rl.addView(image);
rl.addView(truee);
rl.addView(falsee);
return rl;
}
Edit:
I did not realise the OP was asking for a CheckBox before posting. I will leave this up just in case someone wants it.

It's not wise to use buttons as radio buttons. Both are different, have different purposes and the idea is semantically wrong.
Skin your radio buttons as normal buttons.
Here is a good guide on skinning android
http://brainflush.wordpress.com/2009/03/15/understanding-android-themes-and-styles/

Related

How to remove dynamic button on android studio

I add some button with image and animation in my code, the following is my code.
//add diamond to relativelayout
private void addDiamond(){
Drawable img = getContext().getResources().getDrawable( R.drawable.diamond );
img.setBounds( 0, 0, diamondWidth, diamondHeight );
for (int i = 0; i < diamondRow; i++) {
LinearLayout row = new LinearLayout(getContext());
row.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
diamondHeight+120));
for (int j = 0; j < diamondCol; j++) {
Button btnTag = new Button(getContext());
btnTag.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
btnTag.setCompoundDrawables(null, img, null, null);
btnTag.setText("0.0158" + (j + 1 + (i * diamondCol)));
btnTag.setTextColor(Color.WHITE);
btnTag.setTextSize(8);
btnTag.setBackgroundColor(Color.TRANSPARENT);
btnTag.setId(j + 1 + (i * diamondCol));
btnTag.setOnClickListener(btnClick);
row.addView(btnTag);
}
diamond_lyt.addView(row);
}
animate(diamond_lyt);
}
private Button.OnClickListener btnClick = new Button.OnClickListener(){
public void onClick(View v){
Button button = diamond_lyt.findViewById(v.getId());
Toast.makeText(getContext(), String.valueOf(button.getId()), Toast.LENGTH_SHORT).show();
ViewGroup layout = (ViewGroup) button.getParent();
layout.removeView(button);
}
};
Now I wnat to click these button to remove it individually.
But it is very strange in the result.
When I click two column first button, it remove two column last button.
Please how can I solve this problem?
There's nothing wrong with the click, it removes the views correctly as you click on them. I guess whenever you remove a button, the remaining buttons in the row shift towards left creates an illusion which makes you think it removes the wrong button.
If you intend to have a grid-like layout, that the buttons should always stay in their positions on screen, you could try setting the visibility to View.INVISIBLE instead of removing the view, or replace it with an empty view of the same size.
This one too simple.....
Instead of this ...
private Button.OnClickListener btnClick = new Button.OnClickListener(){
public void onClick(View v){
Button button = diamond_lyt.findViewById(v.getId());
Toast.makeText(getContext(), String.valueOf(button.getId()), Toast.LENGTH_SHORT).show();
ViewGroup layout = (ViewGroup) button.getParent();
layout.removeView(button);
}
};
Try this one ....
private Button.OnClickListener btnClick = new Button.OnClickListener(){
public void onClick(View v){
Button button =((Button)v);
((ViewGroup) button.getParent()).removeView(button);
}
};
When Your button click onClick(View v) v give you instance of button. TypeCaste from View to Button and remove it.

Android Butterknife add Textview onClick

I have an activity where the user enters some ingredient info and an add button. How would I add a textview using butterknife? I am currently getting no errors and nothing onscreen so I must be trying to implement this wrong.
I figured it out. this may not be the right way to do it but this is how I accomplished it.
I first add the binds
#BindView(R.id.btnAddIngredient)
Button btnAdd;
#BindView(R.id.addNextBtn2)
Button btnNext;
#BindView(R.id.ingListLayout)
LinearLayout linearLayout;
Then I added this code
#OnClick({
R.id.btnAddIngredient,
R.id.addNextBtn2
})
public void onClick(Button button) {
switch (button.getId()) {
case R.id.btnAddIngredient:
qty = edtxt1.getText().toString();
measurement = edtxt2.getText().toString();
Ingredient = edtxt3.getText().toString();
inputString = qty+" "+measurement+" of "+Ingredient;
TextView ing = new TextView(this);
ing.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
ing.setText(inputString);
linearLayout.addView(ing);
edtxt1.setText(null);
edtxt2.setText(null);
edtxt3.setText(null);
break;
case R.id.addNextBtn2:
//What does this button do
if (jsonArray != null) {
Intent i = new Intent(AddRecipeScreen2.this, AddRecipeScreen3.class);
startActivity(i);
}else
Toast.makeText(mContext, "Please add Ingredients!",
Toast.LENGTH_LONG).show();
break;
}
}

OnClickListener for Dynamically created buttons

I'm new to android Development and I hope you can help me.I created Buttons Dynamically ( Based on the contents of my Database). I also made onclicklistener for those buttons. The problem now is, If I click the buttons, Nothing happens. There is also no error shown in logcat. Why do you think this happened? Any response will be appreciated.
Here is my code on creating buttons:
final LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
cursorCol = scoresDataBaseAdapter.queueCrit(mRowId);
for(cursorCol.move(0); cursorCol.moveToNext(); cursorCol.isAfterLast()){
int Id = Integer.parseInt(cursorCol.getString(cursorCol.getColumnIndex("_id")));
Log.i("_id","_id : "+Id);
String CriteriaButton = cursorCol.getString(cursorCol.getColumnIndex("Criteria"));
Log.i("CriteriaButton","CriteriaButton : " + CriteriaButton);
Button btn = new Button(this);
btn.setText(" " + CriteriaButton + " ");
btn.setId(Id);
btn.setTextColor(Color.parseColor("#ffffff"));
btn.setTextSize(12);
btn.setPadding(10, 10, 10, 10);
btnlayout.addView(btn,params);
btn.setOnClickListener(getOnClickDoSomething(btn));}
Now after my OnCreate, I have the following method to set the onclicklistener
View.OnClickListener getOnClickDoSomething(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
String criteria = button.getText().toString();
if ("Exams".equals(criteria)){
Toast.makeText(getApplicationContext(),"Exams Selected",2).show(); }
else if ("Quizzes".equals(criteria)){
Toast.makeText(getApplicationContext(),"Quizzes Selected",2).show(); }
}
};
}
Change
String criteria = button.getText().toString();
to
String criteria = button.getText().toString().trim();
Inside onClick method use View parameter of onClick method to get Text from pressed button as:
public void onClick(View v) {
Button button = (Button)v;
String selectedText = button.getText().toString();
....your code here
}

Android: Save State of Radio Buttons

Hi I'm trying to create an app for Android and in order to develop it i need to navigate through different pages and questions. For this task I have defined a radiogroup with some radiobuttons. What I want to obtain is each question answered radiobutton and when the user goes thorugh differentes pages the value can be retrieved. I have tried this code that consists of that if there is one selected radiobutton, there arent created new radiobuttons (radiobuttons checked false). However with this code, there is always a selected answer so there is always the same radiobutton selected. I will appreciate some help.
radBotA.setOnCheckedChangeListener(radioCheckChangeListener);
radBotB.setOnCheckedChangeListener(radioCheckChangeListener);
radBotC.setOnCheckedChangeListener(radioCheckChangeListener);
radBotD.setOnCheckedChangeListener(radioCheckChangeListener);
radBotA.setOnClickListener(radioClickListener);
radBotB.setOnClickListener(radioClickListener);
radBotC.setOnClickListener(radioClickListener);
radBotD.setOnClickListener(radioClickListener);
if (radBotA.isChecked()){
Answers[position]="A";
}
else if(radBotB.isChecked()){
Answers[position]="B"; }
else if(radBotB.isChecked()){
Answers[position]="C"; }
else if(radBotC.isChecked()){
Answers[position]="D"; }
else if(radBotD.isChecked()){
Answers[position]="D"; }
else {
radBotA.setChecked(false);
radBotA.setChecked(false);
radBotA.setChecked(false);
radBotA.setChecked(false);
}
bPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
position = position -1;
questions.Previous();
currentQuestion();
}
});
bNext.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
position = position +1;
questions.Next();
currentQuestion();
}
});
private void currentQuestion() {
if (position==0){
bPrevious.setVisibility(View.GONE);
}else{
bPrevious.setVisibility(View.VISIBLE);
}
if (position==nPreguntas-1){
bNext.setVisibility(View.GONE);
}else{
bNext.setVisibility(View.VISIBLE);
}
questions.currentQuestion(this, category);
enunciado.setImageResource(Enunciado[position]);
pregunta.setText(questions.getPregunta());
final RadioButton radBotA = new RadioButton(this);
final RadioButton radBotB = new RadioButton(this);
final RadioButton radBotC = new RadioButton(this);
final RadioButton radBotD = new RadioButton(this);
radBotA.setText("A. " + questions.getRespuestaA());
radBotB.setText("B. " + questions.getRespuestaB());
radBotC.setText("C. " + questions.getRespuestaC());
radBotD.setText("D. " + questions.getRespuestaD());
String nprueba = "Item " + questions.getId() + " de "+ nPreguntas;
NombrePrueba.setText(nprueba);
if (radBotA.isChecked()){
Answers[position]="A";
}
else if(radBotB.isChecked()){
Answers[position]="B"; }
else if(radBotB.isChecked()){
Answers[position]="C"; }
else if(radBotC.isChecked()){
Answers[position]="D"; }
else if(radBotD.isChecked()){
Answers[position]="D"; }
else {
radBotA.setChecked(false);
radBotA.setChecked(false);
radBotA.setChecked(false);
radBotA.setChecked(false);
}
}
thank you all for your time
Edit:
public void save(){
SharedPreferences settings = getSharedPreferences("Answers", 0);
SharedPreferences.Editor e = settings.edit();
e.putBoolean("A0",radBotA.isChecked());
e.putBoolean("B0",radBotB.isChecked());
e.putBoolean("C0",radBotC.isChecked());
e.putBoolean("D0",radBotD.isChecked());
e.putBoolean("A1",radBotA.isChecked());
e.putBoolean("B1",radBotB.isChecked());
e.putBoolean("C1",radBotC.isChecked());
e.putBoolean("D1",radBotD.isChecked());
e.putBoolean("A2",radBotA.isChecked());
e.putBoolean("B2",radBotB.isChecked());
e.putBoolean("C2",radBotC.isChecked());
e.putBoolean("D2",radBotD.isChecked());
e.putBoolean("A3",radBotA.isChecked());
e.putBoolean("B3",radBotB.isChecked());
e.putBoolean("C3",radBotC.isChecked());
e.putBoolean("D3",radBotD.isChecked());
public void load(){
SharedPreferences settings = getSharedPreferences("Answers", 0);
boolean answerA0 = settings.getBoolean("A0", false);
boolean answerB0 = settings.getBoolean("B0", false);
boolean answerC0 = settings.getBoolean("C0", false);
boolean answerD0 = settings.getBoolean("D0", false);
boolean answerA1 = settings.getBoolean("A1", false);
boolean answerB1 = settings.getBoolean("B1", false);
boolean answerC1 = settings.getBoolean("C1", false);
boolean answerD1 = settings.getBoolean("D1", false);
boolean answerA2 = settings.getBoolean("A2", false);
boolean answerB2 = settings.getBoolean("B2", false);
boolean answerC2 = settings.getBoolean("C2", false);
boolean answerD2 = settings.getBoolean("D2", false);
boolean answerA3 = settings.getBoolean("A3", false);
boolean answerB3 = settings.getBoolean("B3", false);
boolean answerC3 = settings.getBoolean("C3", false);
boolean answerD3 = settings.getBoolean("D3", false);
However I don't know how to continue. I v' thinking about the following code but it gives me error and where posicion is the "Page Number":
public void Test(){
switch(posicion){
case(0):
if(answerA0==true){
e.putBoolean("A0",radBotA.isChecked());
}
}
}
}
If I understand you correctly, you want to retrieve some data in other activities. In that case the easiest way would be to use SharedPreferences.
After user answers the question (CheckBox's check state is being changed) you should store your information in SharedPreferences like this:
SharedPreferences settings = getSharedPreferences("Answers", 0); // first argument is just a name of your SharedPreferences which you want to use. It's up to you how you will name it, but you have to use the same name later when you want to retrieve data.
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("questionA", radBotA.isChecked()); // first argument is a name of a data that you will later use to retrieve it and the second argument is a value that will be stored
editor.putBoolean("questionB", radBotB.isChecked());
editor.putBoolean("questionC", radBotC.isChecked());
editor.putBoolean("questionD", radBotD.isChecked());
editor.commit(); // Commit the changes
So now you have those information stored in your internal storage. In other activity, you can retrieve this information:
SharedPreferences settings = getSharedPreferences("Answers", 0);
boolean answerA = settings.getBoolean("questionA", false); // The second argument is a default value, if value with name "questionA" will not be found
boolean answerB = settings.getBoolean("questionB", false);
boolean answerC = settings.getBoolean("questionC", false);
boolean answerD = settings.getBoolean("questionD", false);
I'm working on same application and the solution is that you have to store state of Radio button according to your question Number and for each question there is different key, like this:
final RadioButton rdSelection=(RadioButton)findViewById(mradioOptGroup.getCheckedRadioButtonId());
int child_index=mradioOptGroup.indexOfChild(rdSelection);
switch(mid)
{
case 1:
sharedpreferences.putint("",child_index);
break;
case 2:
sharedpreferences.putint("",child_index);
break;
}
and do like this for all your questions on every next question
and on every previous question you have to store state of radio button of mid+1
where mid is your question number
i just solved this problem , now i am able to save the current state of radio button on every next click and on every previous click i get back the radio state,even at the if the user changed the state by going to previous question or any of the question.

OnClick button ,create a layer in the same form. Android

I m very new to Android.
I want to create a dynamic OnClick button functionality.
OnClick of "+" above , it should create a other layer , like this below.
My confusion , my entire design UI is in layout.xml.
How we can we include another layer in our UI on OnClick of "+" button.
Any input would be helpful.
Thanks !!!
You could do this programatically. XML is for static layouts.
Excuse my pseudo Android:
private LinearLayout root;
public void onCreate(Bundle b){
LinearLayout root = new LinearLayout(this);
root.addChild(createGlucoseReadingView());
setContentView(root);
}
private View createGlucoseReadingView() {
LinearLayout glucoseRoot = new LinearLayout(this);
glucoseRoot.addChild(new TextView(this));
return glucoseRoot;
}
public void onPlusClick(View button){
root.addChild(createGlucoseReadingView());
}
Something along those lines, I've obviosuly left out formatting and adding the layout params to the views, but you get the idea.
In your XML have one Vertical Linear Layout to add and remove EditTexts at runtime, Here I have shown you code I have used in my demos. To handle and maintain the usage.
Onclick of your Add and Minus button click
public void onClick(View view) {
super.onClick(view);
switch (view.getId()) {
case R.id.btnadd:
createTextview(counter);
counter++;
if (counter > 3) {
btnAdd.setVisibility(View.GONE);
btnRemove.setVisibility(View.VISIBLE);
}
break;
case R.id.btnremove:
removeView(counter);
txtoption[counter - 1] = null;
counter--;
if (counter < 3) {
btnAdd.setVisibility(View.VISIBLE);
btnRemove.setVisibility(View.GONE);
}
break;
}
}
Functions to create and remove view
private void createTextview(int index) {
txtoption[index] = new EditText(this);
txtoption[index].setSingleLine(true);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
param.bottomMargin = 10;
txtoption[index].setLayoutParams(param);
txtoption[index].setBackgroundResource(R.drawable.textbox);
txtoption[index].setTypeface(ttfDroidSherif);
lnpolloptions.addView(txtoption[index]);
}
private void removeView(int index) {
lnpolloptions.removeView(txtoption[index - 1]);
}
Your vertical LinearLayout to contain all the edittext childs
LinearLayout lnpolloptions = (LinearLayout) findViewById(R.id.lnpolloptions);
Arrays of edittext to be created of removed at runtime
private EditText[] txtoption = new EditText[4];
Onclick of submit to get value from each textbox
int length = txtoption.length;
for (int i = 0; i < length; i++) {
if (txtoption[i] != null) {
Log.i("Value",""+txtoption[i].getText());
}
}

Categories

Resources