Android using if statement on textview and imagebutton - android

Hello guys i am making simple game that can take point if i click right button.
so there is 5 imagebutton and 1 textview. textview will generate random number 1-5 . and those 5 imagebuttons has 5 different id , so my point is if textview generates 1 number how can i check it its right button using if statement.
if ( textview(current generated number ) == imagebutton(id) ) {
counter++)
something like this can you help me guys? example code would be nice :D

Set the tag value for the buttons
either from xml set Tag attribute
Tag = "1"
or
btn.setTag("1");
Add the buttons corresponding value to its tag and then compare it with tags value
in onClick method you get id of button clicked
Button btn = (Button) findViewById(id);
string valu = btn.getTag();
Now compare the textView value with this tag value.
string txt = textView.getText();
if(txt.equals(valu))
{
// do what you want
}

You could store the button resource IDs an array of int. Then in a common click handler, you could test whether the button clicked was the same as the one randomly selected. Here's a simplistic, minimal example. It assumes you've set and displayed the random number before you get the button clicks.
In your class, define these fields:
private int myButtons[] = null;
private int randomNumber = 0;
In onCreate(), add the following:
myButtons = new int[] {R.id.btn0, R.id.btn1, R.id.btn2, R.id.btn3, R.id.btn4};
Add the method:
public btnClick(View v) {
if (findViewById(myButtons[randomNumber]) == v)
Log.i(TAG, "Correct!");
else
Log.i(TAG, "Incorrect!");
}
Then in your layout XML, define the buttons with your click handler:
<Button
android:id="#+id/btn0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="#string/btn0" />
<Button
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="#string/btn1" />
<Button
android:id="#+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="#string/btn2" />
<Button
android:id="#+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="#string/btn3" />
<Button
android:id="#+id/btn4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="#string/btn4" />

Related

Display the text of a button when clicked in Kotlin

I have a table made of buttons and each button has a text on it. However, I want that text to be invisible unless the button is clicked.
The buttons look like this:
<Button
android:background="#drawable/roundstyle"
android:backgroundTint="#color/c1"
android:id="#+id/btnOne"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="2dp"
android:layout_weight="1"
android:text="#string/i"
tools:ignore="UsingOnClickInXml"
android:onClick="displayText" />
In MainActivity, I tried to implement a function to display the text:
fun displayText(view: View) {
val b = view as Button
val buttonText = b.text.toString()
I think the easiest thing to do would be to use "if", so that if btnOne is not clicked, then the text should be invisible, else, the text should be visible. But I am not sure where to write this code in the Main Activity and how exactly, so that once the button has been clicked, the text remains on the screen.
Could someone help me with this, please?
Thank you.
can try this one by default set the button like this(the most easy solution)
<Button
android:background="#drawable/roundstyle"
android:backgroundTint="#color/c1"
android:id="#+id/btnOne"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="2dp"
android:layout_weight="1"
android:tag = "some text"
tools:ignore="UsingOnClickInXml"
android:onClick="displayText" />
and click handler
fun displayText(view: View) {
val b = view as Button
val btnTag= b.tag.toString()
if (b.text.isEmpty()) {
b.text = btnTag
}
}
You can do this simply by changing the font size of the button text. you can initially set the font size to 0 and then set the right value after user clicked on it.
<Button
android:onClick="displayText"
android:text="Sample Text"
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="64dp"
android:textSize="0sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
To visible the text once
fun displayText(view: View) {
view.setTextSize(TypedValue.COMPLEX_UNIT_SP,12f)
}
This function will toggle the visibility of the text
fun displayText(view: View) {
if(view.textSize == 0f){
view.setTextSize(TypedValue.COMPLEX_UNIT_SP,12f)
}else{
view.setTextSize(TypedValue.COMPLEX_UNIT_SP,0f)
}
}

How do I update the Quantity when user press "+" or "-" button?

Note: This has to be done in Kotlin
I want to update the quantity when the user presses the "+" or the "-" button
enter image description here
I also want the "0" (Quantity) to be aligned between the two buttons.
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="36dp"
android:layout_marginTop="36dp"
android:orientation="vertical"
tools:ignore="HardcodedText">
<TextView
android:id="#+id/Quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="QUANTITY"
android:textSize="23sp" />
<TextView
android:id="#+id/qtr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/Quantity"
android:layout_toRightOf="#+id/add"
android:text="#string/Qtr"
android:textSize="23sp" />
<Button
android:id="#+id/orderbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/add"
android:onClick="order"
android:text="Order" />
<Button
android:id="#+id/add"
android:layout_width="45dp"
android:layout_height="wrap_content"
android:layout_below="#+id/Quantity"
android:layout_marginRight="16dp"
android:text="+" />
<Button
android:id="#+id/sub"
android:layout_width="45dp"
android:layout_height="wrap_content"
android:layout_below="#+id/Quantity"
android:layout_marginLeft="16dp"
android:layout_toRightOf="#+id/qtr"
android:text="-" />
</RelativeLayout>
And this is the Kotlin file code (MainActivity.kt)
package com.example.demoapplicaltion
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Write code here
}
}
First create a counter above your main method:
var quantity: Int = 0
Next set the click listeners to your two buttons within your onCreate():
findViewById<Button>(R.id.add).setOnClickListener{
quantity++
updateValue()
}
findViewById<Button>(R.id.min).setOnClickListener{
quantity--
updateValue()
}
and finally create the updateValue() method:
fun updateValue(){
findViewById<TextView>(R.id.Quantity).text = quantity
}
I'll give you a step by step recepy instead of writing the whole code here.
Step 1
In your MainActivity you need some sort of reference to your two buttons and to the textview from the xml in order to do anything with them. The easiest way is to use the findViewById() fuction.
For example you would need a variable like
var addButton: Button? = null
in your Activity.
Step 2
To assgin the button from the xml to this varibale call
addButton = findViewById( R.id.add )
Step 3
Now that the button from the xml is assigned to your variable inside the activity you can access it to define what should happen if the button is clicked. Like for example:
addButton.setOnClickListener {
code that increases the quantity, sth like:
val oldQuantity = quantityTextView.text.toInt()
quantityTextView.text = oldQuantity + 1
}
To see findViewById work have a look at: https://www.tutorialkart.com/kotlin-android/access-a-view-programmatically-using-findviewbyid/
Note that there are better, but a bit more complex ways to link between xml and Activity like ViewBinding: https://developer.android.com/topic/libraries/view-binding
First get current quantity from shown textview, like this
String currentQuant = qtr.gettext().toString();
then parse into Integer
int quantity = Integer.parseInt(currentQuant);
now you have the current quantity as int just increment it, like this
quantity ++ ;
then
qtr.settext(String.valueOf(quantity));

Use multiple edit text and perform calculation

I am trying to take multiple input using edit text and i want to perform calculation .I am trying to develop a freight calculator in this one field type of delivery normal or express and other field is weight of package. i have no idea how to take input from both and calculate price.
This is how i do it.
To collect input from user use EditText,
sample shown below replicate this with different ID for edit text.
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your quantity here"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="input space for user"
android:textSize="15sp"
android:id="#+id/edit1"
android:inputType="number" />
</LinearLayout>
use TextView to display answer
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/answer"
android:textSize="25sp"/>
Create a button that user can press when he fills up the inputs required
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate"
android:onClick="simulate"/>
now in your JAVA file make an onClick event handler
public void simulate(View view) {
EditText edit1 = (EditText) findViewById(R.id.edit1);
EditText edit2 = (EditText) findViewById(R.id.edit2);
l1 = Integer.valueOf(edit1.getText().toString());
l2 = Integer.valueOf(edit2.getText().toString());
//perform your calculation here
TextView rs1 = (TextView)findViewById(R.id.result);
rs1.setText(""+ your answer);
}
Create a reference to both EditText fields at the class level, for example:
private EditText firstEditText;
private EditText secondEditText;
Within the the onCreate() function in your Activity, or the onCreateView() within your Fragment, bind the reference to your view:
Activity
firstEditText = (EditText) findViewById(R.id.edit_text_first);
secondEditText = (EditText) findViewById(R.id.edit_text_second);
Fragment
firstEditText = (EditText) view.findViewById(R.id.edit_text_first);
secondEditText = (EditText) view.findViewById(R.id.edit_text_second);
Then on some click event or at whatever point you'll want to pull the value from both of the EditText's:
String firstValue = firstEditText.getText().toString();
String secondValue = secondEditText.getText().toString();
Now you're free to parse/calculate/interrogate the values however you want.

use checkbox to send textview value to another activity using image button onclick

i am making a program, in which i am using 3 checkboxes for the item variations along with 3 textviews for their prices, now i want to know, whenever user will click on checkbox1 then price appears in textview1 send to next activity, like in second activity you have selected : checkbox1 $2.00,i want to do this using image button for add to order, please write some brief code how is it possible for me. Here i am placing main.xml code:-
<TextView
android:id="#+id/regular"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/var1"
android:layout_marginLeft="40dp"
android:text="$2.00"
android:textColor="#343434"
android:textSize="15dip" />
<CheckBox
android:id="#+id/var2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/cost"
android:layout_toRightOf="#+id/var1"
android:text="Small" />
<TextView
android:id="#+id/small"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/var2"
android:layout_toRightOf="#+id/var1"
android:layout_marginLeft="40dp"
android:text="$1.00"
android:textColor="#343434"
android:textSize="15dip" />
<CheckBox
android:id="#+id/var3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/cost"
android:layout_toRightOf="#+id/var2"
android:text="Large" />
<TextView
android:id="#+id/large"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/var3"
android:layout_toRightOf="#+id/var2"
android:layout_marginLeft="40dp"
android:text="$3.00"
android:textColor="#343434"
android:textSize="15dip" />
<ImageButton
android:id="#+id/add_order"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:src="#drawable/add_order" />
You need to add an onClickListener to your ImageButton. Now if the onClick method is called retrieve the state of the checkboxes and determine the price of the item.
This price can now be added to the Intent that you use to start the next Activity.
Use the setExtra and getExtra Methods of the Intent class as explained in this Tutorial
Try this code
public class MainActivity extends Activity {
private ImageButton btn;
private TextView txtSmall, txtMed,txtLarge;
private CheckBox chkSmall, chkLarge;
private String strSmall, strLarge;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Checkbox Declaration
chkSmall = (CheckBox)findViewById(R.id.var2);
chkLarge = (CheckBox)findViewById(R.id.var3);
//TextView Declaration
txtSmall = (TextView)findViewById(R.id.small);
txtLarge = (TextView)findViewById(R.id.large);
//ImageButton
btn = (ImageButton)findViewById(R.id.add_order);
//RESET VALUES
strSmall = txtSmall.getText().toString();
strLarge = txtLarge.getText().toString();
btn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if(chkSmall.isChecked()){
Toast.makeText(MainActivity.this, "SMALL CHECKBOX SELECTED", Toast.LENGTH_SHORT).show();
txtLarge.setText(txtSmall.getText().toString());
}
else if(chkLarge.isChecked()){
Toast.makeText(MainActivity.this, "LARGE CHECKBOX SELECTED", Toast.LENGTH_SHORT).show();
txtSmall.setText(txtLarge.getText().toString());
}
else{
Toast.makeText(MainActivity.this, "RESET Called", Toast.LENGTH_SHORT).show();
txtSmall.setText(strSmall);
txtLarge.setText(strLarge);
}
}
});
}
Here Your XML code set to layout.

Set selected index of an Android RadioGroup

Is there a way to set the selected index of a RadioGroup in android, other than looping through the child radiobuttons and selecting checking the radio button at the selected index?
Note: I am populating the Radio Button Group at run time.
If your radio group is defined in a layout xml file, each button can be assigned an id. Then you just check a button like this
radioGroup.check(R.id.myButtonId);
If you created your radio group programmatically (I'm not even sure how you do this...), you might want to consider creating a special layout xml file just for the radio group so that you can assign R.id.* ids to the buttons.
Please see the answer below if you are, in fact, looking to set the radio button group by index, see the answer below.
((RadioButton)radioGroup.getChildAt(index)).setChecked(true);
Question said "set selected INDEX", here's how to set it by index:
((RadioButton)radioGroup.getChildAt(index)).setChecked(true);
........
Additional info: It seems that Google wants you to use id instead of index, because using id is more bug proof. For example, if you have another UI element in your RadioGroup, or if another developer re-orders the RadioButtons, the indices might change and not be what you expected. But if you're the only developer, this is totally fine.
you can do findViewById from the radio group .
((RadioButton)my_radio_group.findViewById(R.id.radiobtn_veg)).setChecked(true);`
Siavash's answer is correct:
((RadioButton)radioGroup.getChildAt(index)).setChecked(true);
But be aware that a radioGroup can contain views other than radioButtons -- like this example that includes a faint line under each choice.
<RadioGroup
android:id="#+id/radioKb"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/kb1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:button="#null"
android:drawableRight="#android:drawable/btn_radio"
android:text="Onscreen - ABC" />
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#33000000" />
<RadioButton
android:id="#+id/kb2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:button="#null"
android:drawableRight="#android:drawable/btn_radio"
android:text="Onscreen - Qwerty" />
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#33000000" />
<RadioButton
android:id="#+id/kb3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:button="#null"
android:drawableRight="#android:drawable/btn_radio"
android:text="Standard softkey" />
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#33000000" />
<RadioButton
android:id="#+id/kb4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:button="#null"
android:drawableRight="#android:drawable/btn_radio"
android:text="Physical keyboard" />
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#33000000" />
</RadioGroup>
In this case using an index of 1, for example, would generate an error. The item at index 1 is the first separator line -- not a radioButton. The radioButtons in this example are at indexes 0, 2, 4, 6.
This Worked For me, I created radio button dynamically by
private void createRadioButton() {
RadioButton[] rb = new RadioButton[5];
RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
1.0f);
radioGroup.setOrientation(RadioGroup.HORIZONTAL);
for (int ID = 0; ID < 5; ID++) {
rb[ID] = new RadioButton(this);
rb[ID].setLayoutParams(layoutParams);
rb[ID].setText("Button_Text");
radioGroup.addView(rb[ID]); //the RadioButtons are added to the radioGroup instead of the layout
}
}
Now Check a button using,
int radio_button_Id = radioGroup.getChildAt(index).getId();
radioGroup.check( radio_button_Id );
Inside onBindViewHolder set the tag to Button Group
#Override
public void onBindViewHolder(final CustomViewHolder holder, final int position) {
...
holder.ButtonGroup.setTag(position);
}
and in the ViewHolder
ButtonGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
...
int id = radioGroup.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton) radioGroup.findViewById(id);
int clickedPos = (Integer) radioGroup.getTag();
packageModelList.get(clickedPos).getPoll_quest()
}
Using Kotlin you can make it by
(radio_group_id.getChildAt(index) as RadioButton).isChecked = true
or
radio_group_id.check(R.id.radio_button_id)

Categories

Resources