Android java code to add + and - button beside edittext - java

for(int i=0;i<j.size();i++)
{
TableLayout.LayoutParams tableRowParams=
new TableLayout.LayoutParams
(TableLayout.LayoutParams.FILL_PARENT,TableLayout.LayoutParams.WRAP_CONTENT);
JsonObject jb = (JsonObject) j.get(i);
String item = jb.get("item").getAsString();
String unit = jb.get("unit").getAsString();;
String price = jb.get("price").getAsString();;
TableRow tbrow1 = new TableRow(this);
TextView tv01 = new TextView(this);
tv01.setText(item);
tv01.setTextColor(Color.BLACK);
tbrow1.addView(tv01);
TextView tv11 = new TextView(this);
tv11.setText(unit);
tv11.setTextColor(Color.BLACK);
tbrow1.addView(tv11);
TextView tv21 = new TextView(this);
tv21.setText(price);
tv21.setTextColor(Color.BLACK);
tbrow1.addView(tv21);
Button button = new Button(this);
button.setText("+");
button.setTag(item);
tbrow1.addView(button);
final String id_ = (String) button.getTag();
EditText edText = new EditText(this);
edText.setInputType(InputType.TYPE_CLASS_NUMBER);
//edText.setText(0);
tbrow1.addView(edText);
Button button1 = new Button(this);
button1.setText("-");
button.setTag(item);
tbrow1.addView(button1);
final String id1_ = (String) button.getTag();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getBaseContext(), "button clicked for "+id_, Toast.LENGTH_LONG).show();
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getBaseContext(), "button clicked for "+id1_, Toast.LENGTH_LONG).show();
}
})
}
I'm developing Android app for grocery shop . I'm getting itms details in json
Depending on items number I'm creating dynamic rows.
Now I want to add + and - button in each row .
I want it programmatically
How to to do it.
Example: + - button in zomato while adding food to cart .
As i click + or - button that corresponding item number should increment/decrement

You can use this library. It is a simple Android library to implement a number counter with increment and decrement buttons.
https://github.com/ashik94vc/ElegantNumberButton

try this,
MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView textViewCount;
int count=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewCount=findViewById(R.id.textViewCount);
textViewCount.setText(""+count);
}
public void itemSubtractClick(View view) {
if (count>0)
textViewCount.setText(""+count--);
else
Toast.makeText(this, "not allowed", Toast.LENGTH_SHORT).show();
}
public void itemAddClick(View view) {
textViewCount.setText(""+count++);
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/shape"
android:gravity="center"
android:orientation="horizontal">
<ImageView
android:onClick="itemSubtractClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/icon_subtract" />
<TextView
android:id="#+id/textViewCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#17F44336"
android:padding="10dp"
android:text="2"
android:textSize="18sp" />
<ImageView
android:onClick="itemAddClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/icon_add" />
</LinearLayout>

Related

Dialog with multiple textview

i need to add 5 text view in my code. For now there is only one and it is used to put a marker in google maps. I would like that in addition to this you could put another 4 data insertions like (description, age, work, hobbys).Below I also put the custom dialog I made can you check if it's okay? Feel free to ask for anything. How can I do?
add_address.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
View viewcustom = getLayoutInflater().inflate(R.layout.custom_dialog, null);
EditText edt1 = view.findViewById(R.id.Description);
EditText edt2 = view.findViewById(R.id.Age);
EditText edt3 = view.findViewById(R.id.Hobby);
EditText edt4 = view.findViewById(R.id.City);
EditText edt5 = view.findViewById(R.id.address);
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(requireContext())
.setView(viewcustom)
.setPositiveButton("Ok", (dialogInterface, i) -> {
String description = edt1.getText().toString();
String age = edt2.getText().toString();
String Hobby = edt3.getText().toString();
String City = edt4.getText().toString();
String address = edt5.getText().toString();
Toast.makeText(requireContext(), description, Toast.LENGTH_SHORT).show();
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser.getUid()).child("address");
reference.setValue(address);
});
alertDialog.setNegativeButton("Cancel", null);
alertDialog.create().show();
//startAutoCompleteIntent();
}
});
Customdialog.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Text 1"
android:id="#+id/Description" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Text 2"
android:id="#+id/Age" />
<EditText
android:id="#+id/Hobby"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:hint="Text 3" />
<EditText
android:id="#+id/City"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Text 4" />
<EditText
android:id="#+id/Marker"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Text 5" />
</LinearLayout>
You have to provide your own custom view and then you have to retrieve your EditTexts with findViewByID()
View view = getLayoutInflater().inflate(R.layout.custom_dialog, null);
EditText edt1 = view.findViewById(R.id.Description);
// get other EditTexts here
final Dialog alertDialog = new Dialog(activity);
alertDialog.setView(view);
alertDialog.setPositiveButton("Ok", (dialogInterface, i) -> {
String description = edt1.getText().toString();
//other stuff
});
Entire sample inspired from your code
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(LayoutInflater.from(this));
setContentView(binding.getRoot());
binding.fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
View viewcustom = getLayoutInflater().inflate(R.layout.custom_dialog, null);
EditText edt1 = viewcustom.findViewById(R.id.Description);
EditText edt2 = viewcustom.findViewById(R.id.Age);
EditText edt3 = viewcustom.findViewById(R.id.Hobby);
EditText edt4 = viewcustom.findViewById(R.id.City);
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this)
.setView(viewcustom)
.setPositiveButton("Ok", (dialogInterface, i) -> {
String description = edt1.getText().toString();
String age = edt2.getText().toString();
String Hobby = edt3.getText().toString();
String City = edt4.getText().toString();
Toast.makeText(MainActivity.this, description, Toast.LENGTH_SHORT).show();
});
alertDialog.setNegativeButton("Cancel", null);
alertDialog.create().show();
}
});
}
}

I can't set the button width inside the table view

I'm doing an android application where I have to dynamically put a button inside the table row. The problem is that the button that I create is stretched as in the image below:
I also put some of the application code here below so you can understand better.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_punteggio);
showAlertDialog_modality(R.layout.dialog_change_modality);
final TableLayout tableLayout = findViewById(R.id.tableLayout);
final RelativeLayout relativeLayout = findViewById(R.id.relativeLayout);
final Button btn_settings = findViewById(R.id.btn_settings);
Bundle datipassati = getIntent().getExtras();
String player = datipassati.getString("players");
giocatore = player.split("%");
Log.d("TAG", "array: " + giocatore[0]);
for (int i = 0; i < giocatore.length; i++) {
punti[i] = 0;
TableRow tbrow = new TableRow(this);
final TextView t3v = new TextView(this);
txPunti[i] = t3v;
//------------------------- Textview Player
final TextView t1v = new TextView(this);
t1v.setText(giocatore[i].toUpperCase());
t1v.setTextColor(Color.BLACK);
t1v.setGravity(Gravity.CENTER);
t1v.setTextSize(20);
t1v.setWidth(400);
tbrow.addView(t1v);
//-------------------- BTN MENO
Button btnMeno = new Button(this);
btnMeno.setText("-");
btnMeno.setTextColor(Color.BLACK);
btnMeno.setGravity(Gravity.CENTER);
tbrow.addView(btnMeno);
btnMeno.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
removepoint(t3v);
}
});
// --------------------- TEXT VIEW PUNTI
t3v.setText(punti[i]+"");
t3v.setTextSize(25);
t3v.setMaxWidth(150);
t3v.setPadding(20,0,20,0);
t3v.setTypeface(t3v.getTypeface(), Typeface.BOLD);
t3v.setTextColor(Color.RED);
t3v.setGravity(Gravity.CENTER);
tbrow.addView(t3v);
//----------------------------- BTN PIU
Button btnPiu = new Button(this);
btnPiu.setBackground(ContextCompat.getDrawable(Activity_punteggio.this, R.drawable.ic_add_circle_black_24dp));
btnPiu.setTextColor(Color.BLACK);
btnPiu.setGravity(Gravity.CENTER);
tbrow.addView(btnPiu);
btnPiu.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addPoint(t3v, t1v);
}
});
tableLayout.addView(tbrow);
}
btn_settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showAlertDialog_modality(R.layout.dialog_change_modality);
}
});
}
Here's also the xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Activity_punteggio">
<Button
android:id="#+id/btn_settings"
android:layout_width="55dp"
android:layout_height="32dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="0dp"
android:layout_marginRight="1dp"
android:background="#android:color/transparent"
android:drawableBottom="#drawable/ic_settings_black_24dp" />
<TextView
android:id="#+id/title_player"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="Chip-Chop"
android:textSize="25dp"
android:textStyle="bold|italic" />
<TableLayout
android:id="#+id/tableLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="80dp">
</TableLayout>
</RelativeLayout>
I hope you could help me.
Please check this solution. setImageResource is the method assign
image resource. Set background method is recommended for the
background of the button.
ImageButton btnPiu = new ImageButton(this);
btnPiu.setImageDrawable(ContextCompat.getDrawable(Activity_punteggio.this, R.drawable.ic_add_circle_black_24dp));
btnPiu.setTextColor(Color.BLACK);
btnPiu.setGravity(Gravity.CENTER);
tbrow.addView(btnPiu);
btnPiu.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addPoint(t3v, t1v);
}
});
tableLayout.addView(tbrow);
I used ImageButton other than Button.
setImageDrawable
try to edit android:layout_height="32dp" to android:layout_height="55dp"
android:id="#+id/btn_settings"
android:layout_width="55dp"
android:layout_height="55dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="0dp"
android:layout_marginRight="1dp"
android:background="#android:color/transparent"
android:drawableBottom="#drawable/ic_settings_black_24dp" />
I hope it will work with you .
THIS is make very complex coding, Make it simpler.Don't create whole row dynamically in FOR loop. Instead of that
First Create Separate XML for that row.
Write Below code and your row append into tablelayout.
for (int i = 0; i < giocatore.length; i++) {
View trView = LayoutInflater.from(getActivity()).inflate(R.layout.xmlID,null);
TextView lblGuestName;
lblGuestName = trView.findViewById(R.id.lbl);
lblGuestName.setText("Guest 1");
tableLayout.addView(trView);
}
This Way you easily configure any complex row in tablelayout. No need to make it dynamically.
Feel free to reply.

Country code is not getting from country code picker in Android

I am developing an signup activity in android app. I want show the country telephone code(get the country from device). It may show the list of countries containing with flag, country telephone code, country name. I get the code of country code picker from https://github.com/mukeshsolanki/country-picker-android . It contain the complete code. I want to set the default country is in the phone.
TelephonyManager tm = (TelephonyManager)this.getSystemService(this.TELEPHONY_SERVICE);
String countryCodeValue = tm.getNetworkCountryIso();
System.out.println("country = "+country);
When i using this code i get the country code "in". But i want to display telephone code and flag, name. When i open the screen. I want to display it automatically.
My code is shown below
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#color/colorBackground"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fitsSystemWindows="true">
<LinearLayout
android:layout_gravity="center_vertical"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="56dp"
android:paddingLeft="24dp"
android:paddingRight="24dp">
<ImageView
android:background="#drawable/logo"
android:layout_gravity="center_horizontal"
android:layout_width="150dp"
android:layout_height="150dp" />
<Button
android:text="Country"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/buttonCountry" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:backgroundTint="#d11f08"
android:entries="#array/android_dropdown_arrays"
android:padding="5dp" />
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/editTextPhone"
android:layout_width="match_parent"
android:layout_height="44dp"
android:inputType="phone"
android:hint="Password"/>
</android.support.design.widget.TextInputLayout>
<android.support.v7.widget.AppCompatButton
android:id="#+id/buttonSubmit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:textColor="#color/colorAccent"
android:layout_marginTop="24dp"
android:layout_marginBottom="24dp"
android:padding="12dp"
android:text="Login"/>
</LinearLayout>
</ScrollView>
Main.Activity
public class MainActivity extends AppCompatActivity {
EditText editText;
Button button;
Button buttonCountry;
private Spinner spinner1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editTextPhone);
button = (Button) findViewById(R.id.buttonSubmit);
buttonCountry = (Button) findViewById(R.id.buttonCountry);
spinner1 = (Spinner) findViewById(R.id.spinner1);
TelephonyManager tm = (TelephonyManager)this.getSystemService(this.TELEPHONY_SERVICE);
String countryCodeValue = tm.getNetworkCountryIso();
System.out.println("country = "+countryCodeValue);
//String mPhoneNumber = tm.getLine1Number(); //not getting phone number
//System.out.println("phone no = "+mPhoneNumber);
buttonCountry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
spinner1.setOnItemSelectedListener(new ItemSelectedListener());
final CountryPicker picker = CountryPicker.newInstance("Select Country");
picker.show(getSupportFragmentManager(), "COUNTRY_PICKER");
picker.setListener(new CountryPickerListener() {
#Override
public void onSelectCountry(String name, String code, String dialCode, int flagDrawableResID) {
// Implement your code here
Log.d("LOGTAG", "output1 : name = "+name+" code = "+code+" dialcode = "+dialCode+" flag = "+flagDrawableResID);
picker.dismiss();
}
});
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
public class ItemSelectedListener implements AdapterView.OnItemSelectedListener {
//get strings of first item
String firstItem = String.valueOf(spinner1.getSelectedItem());
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (firstItem.equals(String.valueOf(spinner1.getSelectedItem()))) {
// ToDo when first item is selected
} else {
Toast.makeText(parent.getContext(),
"You have selected : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_LONG).show();
// Todo when item is selected by the user
}
}
#Override
public void onNothingSelected(AdapterView<?> arg) {
}
}
}
Reference : https://github.com/hbb20/CountryCodePickerProject
try to get country code using Lat, long
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
try {
List<Address> addressList = geocoder.getFromLocation(
lati, longi, 1); // lati : Latitude ,longi : Longitude
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
code=addressList.get(0).getCountryCode();
System.out.println("code :: "+addressList.get(0).getCountryCode());
}
} catch (IOException e) {
Log.e(TAG, "Unable connect to Geocoder", e);
}
String locale = context.getResources().getConfiguration().locale.getCountry();
You can use this library
Click here
by then you can do this
new DialogPlusBuilder().blurBackground()
.buildCountriesListDialog(true,new DialogPlus.CountriesDialogListener() {
#Override
public void onItemClicked(CountryDataModel countryDataModel, DialogPlus dialogPlus) {
super.onItemClicked(countryDataModel, dialogPlus);
Toast.makeText(MainActivity.this,countryDataModel.getName()+ countryDataModel.getPhone_code(), Toast.LENGTH_SHORT).show();
}
})
.show(this.getSupportFragmentManager(), "Countries List Dialog");

Second Click Returns to the original text

Im pretty new to Java and xml and i've run into a problem. I've created an app that displays text and then when a button is hit it changes the text, the problem i have is i would like for the text to return to the original when i hit the button a second time
final TextView ad1 = (TextView) findViewById(R.id.t5);
final Button b1 = (Button) findViewById(R.id.b1);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
ad1.setText("random text");
}
});
}
<TextView
android:id="#+id/t5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/t4"
android:layout_margin="5dp"
android:gravity="center"
android:text="#string/t5"
android:textColor="#ffffff"/>
<Button
android:id="#+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/t5"
android:layout_centerHorizontal="true"
android:layout_margin="10dp"
android:layout_marginTop="14dp"
android:text="#string/b1"
android:textColor="#ffffff" />
Try this :
b1.setOnClickListener(new View.OnClickListener()
{
private String originalText = null;
public void onClick(View v)
{
if (originalText == null) originalText = ad1.getText().toString();
if (ad1.getText().toString().equals(originalText))
{
// Setting a new text
ad1.setText("random text");
}
else
{
// Setting back the original text
ad1.setText(originalText);
}
}
});
This does the trick.
String newString = "Whoa!";
String lastString;
public void action_Clicked(View view){
switch(view.getId()){
case R.id.button1:
exchange();
break;
}
}
private void exchange(){
lastString = text.getText().toString();
text.setText(newString);
newString = lastString;
}

TextView isn't updating in Android

I'm making a simple "novelty" app that counts how many sneezes are done, it's more of a fun app that builds up experience until I do my huge project during the summer. I have two buttons, one adds a sneeze and the other clears how many sneezes there currently are. It holds the highest number of sneezes that there were previously. The problem is, the TextViews never update, they only initialize to zero. I used a Toast.makeText() to make sure that the buttons are working (they are). Any help is appreciated. Thanks
Java code:
public class MainActivity extends ActionBarActivity {
private int record_number = 0;
private int current_number = 0;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
Button add_one = (Button) findViewById(R.id.addone);
Button clear_1 = (Button) findViewById(R.id.clear);
add_one.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
current_number += 1;
Toast.makeText(MainActivity.this, "Button Clicked " + current_number, Toast.LENGTH_SHORT).show();
}
});
clear_1.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
current_number = 0;
Toast.makeText(MainActivity.this, "Button Clicked", Toast.LENGTH_SHORT).show();
}
});
TextView rec_text = (TextView) findViewById(R.id.record_num);
TextView cur_text = (TextView) findViewById(R.id.current_num);
if (current_number >= record_number)
{
record_number = current_number;
}
rec_text.setText(String.valueOf(record_number));
cur_text.setText(String.valueOf(current_number));
}
}
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.michail.sneezecounter.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Sneeze Counter"
android:id="#+id/title"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Record Number of Sneezes:"
android:id="#+id/textView"
android:layout_below="#+id/title"
android:layout_centerHorizontal="true"
android:layout_marginTop="72dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add one Sneeze"
android:id="#+id/addone"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="76dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear Current Number of Sneezes"
android:id="#+id/clear"
android:layout_marginBottom="13dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/record_num"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"
android:singleLine="false" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Current Number of Sneezes:"
android:id="#+id/currentLabel"
android:layout_centerVertical="true"
android:layout_alignRight="#+id/textView"
android:layout_alignEnd="#+id/textView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_below="#+id/currentLabel"
android:layout_alignLeft="#+id/record_num"
android:layout_alignStart="#+id/record_num"
android:layout_marginTop="21dp"
android:id="#+id/current_num" />
</RelativeLayout>
You need to update the text of the TextViews inside the onClickListeners. In fact, all your logic for counting, clearing, and recording the record needs to be done in your onClickListeners (or methods called by them). Right now you only do it once in onCreate, then never again. You can do this in onCreate:
final TextView cur_text = (TextView) findViewById(R.id.current_num);
add_one.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
current_number += 1;
cur_text.setText(Integer.toString(current_number);
}
});
And similar for the other TextView & onClickListener.
You only set the contents of your TextViews once. You should update them every time you get a click event. Specifically:
add_one.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
current_number += 1;
if (current_number >= record_number)
{
record_number = current_number;
rec_text.setText(String.valueOf(record_number));
}
cur_text.setText(String.valueOf(current_number));
}
});
clear_1.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
current_number = 0;
cur_text.setText(String.valueOf(current_number));
}
});
NOTE: if your variables current_number, record_number, cur_text, and rec_text aren't already declared as class member variables, you'll want to do that do that so that they're accessible once you leave the scope of the method you're doing all this in (I assume it's onCreate(...).
What you are going to need to do here is update the labels during the on click events of the button. You currently only update them on activity create. This doesn't execute every time there is a click. Can I answer any questions about the fixed up version below?
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
final TextView rec_text = (TextView) findViewById(R.id.record_num);
final TextView cur_text = (TextView) findViewById(R.id.current_num);
Button add_one = (Button) findViewById(R.id.addone);
Button clear_1 = (Button) findViewById(R.id.clear);
add_one.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
current_number += 1;
if (current_number >= record_number)
record_number = current_number;
cur_text.setText(String.valueOf(current_number));
rec_text.setText(String.valueOf(record_number));
}
});
clear_1.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
current_number = 0;
cur_text.setText(String.valueOf(current_number));
rec_text.setText(String.valueOf(record_number));
}
});
cur_text.setText(String.valueOf(current_number));
rec_text.setText(String.valueOf(record_number));
}

Categories