I want a central way to control my buttons - java

Hi I have 2 lines each with a name textfield, 2 buttons and a textfield to show the amount. There will be more lines later.
I want 1 button to add 1 to the amount and the other to decrease the amount by 1.
But I don't know how to get the ID from the button I press. I have gotten this far.
I hope someone can let me know. How I can get the indexvalue depending on which button is pressed.
public class MainActivity extends AppCompatActivity {
private ArrayList<Integer> ButtonUp;
private ArrayList<Integer> Amount;
private ArrayList<Integer> ButtonDown;
int ArrayIndex = 0;
int Value = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButtonUp();
Amount();
ButtonDown();
}
// ArrayList ButtonUp
public void ButtonUp(){
ButtonUp.add(R.id.Bup1);
ButtonUp.add(R.id.Bup2);
}
// ArrayList Amount
public void Amount(){
Amount.add(R.id.Aantal1);
Amount.add(R.id.Aantal2);
}
// ArrayList ButtonDown
public void ButtonDown() {
ButtonDown.add(R.id.Bdown1);
ButtonDown.add(R.id.Bdown2);
}
// Get position ArrayList on press
// Publish new Value
public void buttonPress(View v) {
switch (v.getId()) {
case R.id.Bup1:
SetAmountUp(id);
displayQuantity(Value);
break;
case R.id.Bup2:
SetAmountUp(R.id.Bup2);
displayQuantity(Value);
break;
case R.id.Bdown1:
SetAmountDown(R.id.Bdown1);
displayQuantity(Value);
break;
case R.id.Bdown2:
SetAmountDown(R.id.Bdown1);
displayQuantity(Value);
break;
}
}
public void SetAmountUp(int indexNumberUp){
Value = Amount.get(ButtonUp.indexOf(indexNumberUp));
Value++;
Amount.set(ArrayIndex,Value);
}
public void SetAmountDown(int indexNumberDown){
Value = Amount.get(ButtonDown.indexOf(indexNumberDown));
Value--;
Amount.set(ArrayIndex,Value);
}
// Publish number
private void displayQuantity(int NewAmount) {
int ID = Amount.get(ArrayIndex);
TextView quantityTextView = (TextView) findViewById(ID);
quantityTextView.setText(NewAmount);
}
}

In the layout, declare an unique id to each button, then add android:onClick="increment" to each button.
In your class, create the method
public void increment(View view) {
switch (view.getId()){
case R.id.yourbuttonid1:
// do what you whant
break;
case R.id.yourbuttonid2:
// do with second editext
break
// ....
}
}
Same approach to decrease method.

It will be much easier for you if you used a recyclerView for that

Related

how to take default value of an edittext as 0?

I am trying to make a simple android app in which 2 text fields are there.input range is 0 to 15. If the number is in range than addition is performed.
i have implemented input varification so now if the edit text is empty it shows empty field warning. but calculation is not done. what i want is if the field is empty is should show the error but also do the addition by take default value as 0.
here is my code
public class MainActivity extends AppCompatActivity {
private EditText check,check2;
private TextView textView;
private TextInputLayout checkLay,checkLay2;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeWidgets();
initializeListeners();
}
private void initializeWidgets(){
check=findViewById(R.id.check);
check2=findViewById(R.id.check2);
checkLay2=findViewById(R.id.checkLay2);
checkLay=findViewById(R.id.checkLay);
button=findViewById(R.id.button);
textView=findViewById(R.id.textView);
}
private void initializeListeners() {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signUp();
}
});
}
private void signUp(){
boolean isVailed=true;
int a1,a2;
String one=check.getText().toString();
String two=check2.getText().toString();
if(one.isEmpty()){
checkLay.setError("YOu need to enter something");
isVailed=false;
}
else {
if (one.length() > 0)
{
a1=Integer.parseInt(one);
if(a1> 15){
checkLay.setError("quiz marks must be less than 15");
isVailed=false;
}
else if(a1 <=15)
{
checkLay.setErrorEnabled(false);
isVailed=true;
}
}
}
if(two.isEmpty()){
checkLay2.setError("You need to enter something");
isVailed=false;
}
else{
if (two.length() > 0)
{
a2=Integer.parseInt(two);
if(a2 > 15)
{ checkLay2.setError("quiz marks must be less than 15");
isVailed=false;
}
else
if(a2 <=15)
{
checkLay2.setErrorEnabled(false);
isVailed=true;
}
}
if(isVailed)
{
int total;
a1=Integer.parseInt(one);
a2=Integer.parseInt(two);
total=a1+a2;
textView.setText(String.valueOf(total));
}
}
I would do it differently but for your specific question
if(one.isEmpty()){
checkLay.setError("YOu need to enter something");
isVailed=false;
}
Change to
if(one.isEmpty()){
checkLay.setError("YOu need to enter something");
a1=0;
}
Same for the two.isEmpty()
If a field is empty you set isVailed to false and thus say not to add the numbers. Instead you want to set the corresponding number to zero and let isVailed be true:
if(one.isEmpty()){
checkLay.setError("YOu need to enter something");
a1 = 0;
}
and
if(two.isEmpty()){
checkLay2.setError("You need to enter something");
a2 = 0;
}
Also throw off the lines
a1=Integer.parseInt(one);
a2=Integer.parseInt(two);
You already convert inputs to a1 and a2 earlier.
A piece of advice: you have doubled code. It's better to use functions for such pieces of codes.
add this line in your initializeWidgets function
yourEditText.setText(0);
follow link for more help: duplicate
You can create a convenience method to get value from your edittext. The following code will return 0 if edittext is empty else the value from the edittext
private int getIntFromEditText(EditText editText) {
return editText.getText().length()>0 ? Integer.parseInt(editText.getText().toString()):0;
}
Call it by passing EditText as a parameter, e-g
a1=getIntFromEditText(check)

How can I get the value of the ArrayList without returning size = 0?

When I get the value of the arraylist, I get size = 0. I boot the ArrayList in Class Screen1, but I can not get the value of the Class Screen2 cont.
public class Variables {
public Variables() {
}
private int cont = 0;
private int correct = 0;
public int getCont(){
return cont;
}
public void setCont(int cont){
this.cont = cont;
}
public int getCorrect(){
return correct;
}
public void setCorrect(int correct){
this.correct = correct;
}}
Class Screen1
public class Screen1 extends ActionBarActivity {
Variables variables = new Variables();
ArrayList<Variables> variablesArrayList = new ArrayList<Variables>();
public int cont;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen1);
variables.setCorrect(1);
variables.setCont(1);
variablesArrayList.add(variables);
}
public void sendTela1(View view){
cont = variables.getCont();
cont++;
variablesArrayList.get(0).setCont(cont);
}
}
Class Screen 2
This class I'm trying to get the value of ArrayList
public class Screen2 extends ActionBarActivity {
Variables variables = new Variables();
ArrayList<Variables> variablesArrayList = new ArrayList<Variables>();
int cont;
ImageView progressbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen2);
progressbar = (ImageView) findViewById(R.id.progressbar);
//this line, the arraylist is returning size = 0
cont = variablesArrayList.get(1);
switch (cont){
case 1:
progressbar.setImageResource(R.drawable.progressbar1);
break;
case 2:
progressbar.setImageResource(R.drawable.progressbar2);
break;
case 3:
progressbar.setImageResource(R.drawable.progressbar3);
break;
case 4:
progressbar.setImageResource(R.drawable.progressbar4);
break;
case 5:
progressbar.setImageResource(R.drawable.progressbar5);
break;
}}
You're getting a return size of 0 because in screen2 activity you are creating a new list when you do: ArrayList<Variables> variablesArrayList = new ArrayList<Variables>();
To fix this, you need to pass the arraylist you created in screen1 into screen2. You will have to implement parcelable, but that will allow you to pass the data using intents and bundles.
If you create a new object as you are doing in your screen2 with the line
ArrayList<Variables> variablesArrayList = new ArrayList<Variables>();
you will of course receive an empty arrayList. There are multiple ways of sending data from one Activity to another. I suggest you look into bundles and using putExtras and later getExtras via Intents. However, since you have a model class why not use that?
In your model class add
private static ArrayList<Variables> variablesArrayList;
Now add some setters and getters to update and retrieve your list
// getter
public static ArrayList<Variables> getList() {
return variablesArrayList;
}
// setter
public static void setList(ArrayList<Variables> varArryList) {
this.variablesArrayList = varArryList;
}
Now on screen1 set your arrayList and in screen2 (or 3, or 4, or 5, ect) retrieve it! Cheers!

Displaying list values with each button click

How can i display list items on each button click. Lets say there are 4 names in the list. When I press next it displays the first name. Then when you press next it displays the second name and so on.
The only way I think is using the list.get() method. however I dont know how to use the method so that it knows how many values there are in the list and displaying then on each button hit. I think i need to use for method however I hadnt had any luck with it.
public class ZaidimasActivity extends ZaidejaiActivity {
public TextView mPlayer;
public TextView mKlausimas;
public Button mNext;
public Button mBack;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zaidimas);
/** //get the player list from ZaidejaiActivity
Bundle recdData = getIntent().getExtras();
String myVal = recdData.getString("playerList"); */
Intent zaidejuInfo = getIntent();
Bundle extrasBundle = zaidejuInfo.getExtras();
final ArrayList<String> players = extrasBundle.getStringArrayList("playerList");
//show the first players name
mPlayer = (TextView)findViewById(R.id.ZaidejoVardas);
players.size();
mPlayer.setText(players.get(0));
mNext = (Button)findViewById(R.id.KitasBtn);
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPlayer.setText(players.get(1));
}
});
mBack = (Button)findViewById(R.id.GryztiMeniuBtn);
mBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent gryztiMeniu = new Intent(ZaidimasActivity.this, ZaidejaiActivity.class);
startActivity(gryztiMeniu);
}
});
}
Here you go, maintain a variable for storing the global array index and increment it every time the button is clicked.
private int count = 0; // Global array index. Make it as class field
final ArrayList<String> players = extrasBundle.getStringArrayList("playerList");
mPlayer = (TextView)findViewById(R.id.ZaidejoVardas);
players.size();
mPlayer.setText(players.get(0));
mNext = (Button)findViewById(R.id.KitasBtn);
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count++;
mPlayer.setText(players.get((count)%players.size())); //Incrementing global count and making sure it never exceeds the players list size
}
});

Android onClick(View) with switch incorrect case

I have a single OnClickListener instance to direct clicks to multiple other handler methods, generally:
void onClick(View v) {
switch (v.getId()) {
case R.id.viewA:
handleButtonA();
break;
case R.id.viewB:
handleButtonB();
break;
default:
handleDefaultCondition();
break;
}
}
When I click view A, handleButtonA() is called. When I click view B, nothing happens. When I click any other view it calls handleDefaultCondition(). I had the same behavior with a series of if/else if statements, so I don't think the problem is related to my use of switch.
Here is the complete code:
public class MyClickListener implements View.OnClickListener {
public void onClick(View view) {
int viewId = view.getId();
switch (viewId) {
case R.id.time_frag_mark_button:
handleMarkButton(); //just calls dummy method with a Log statement inside for testing
break;
case R.id.finalize_entry_button:
handleFinalizeButton(); //just calls dummy method with a Log statement inside for testing
break;
default:
openTimePickerDialog(view.getId()); //just calls dummy method with a Log statement inside for testing
break;
}
}
}
And an excerpt from my R file:
public static final class id {
public static final int action_settings=0x7f08000e;
public static final int finalize_entry_button=0x7f08000d;
public static final int separator=0x7f080002;
public static final int time_frag_current_time=0x7f080003;
public static final int time_frag_date_string=0x7f080001;
public static final int time_frag_in_label=0x7f08000b;
public static final int time_frag_in_picker=0x7f08000c;
public static final int time_frag_mark_button=0x7f080004;
}
As requested, the code to initialize the listeners:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myClickListener = new MyClickListener();
myTimeFilter = new IntentFilter(Intent.ACTION_TIME_TICK);
myTimeTicker = new MyTimeTicker();
getApplicationContext().registerReceiver(myTimeTicker, myTimeFilter);
systemTime = (TextView) findViewById(R.id.time_frag_current_time);
systemTime.setText(sdf.format(new Date()));
systemDate = (TextView) findViewById(R.id.time_frag_date_string);
outTimeView = (TextView) findViewById(R.id.time_frag_out_picker);
outTimeView.setOnClickListener(myClickListener);
offTimeView = (TextView) findViewById(R.id.time_frag_off_picker);
offTimeView.setOnClickListener(myClickListener);
onTimeView = (TextView) findViewById(R.id.time_frag_on_picker);
onTimeView.setOnClickListener(myClickListener);
inTimeView = (TextView) findViewById(R.id.time_frag_in_picker);
inTimeView.setOnClickListener(myClickListener);
markButton = (Button) findViewById(R.id.time_frag_mark_button);
markButton.setOnClickListener(myClickListener);
//should error check this, only open a new one if one is not in progress
//need to start saving the Entry to disk during onPause() and move this check to onStart() or something
currentEntry = new LogEntry();
}
Have you tried looking to see what ID is output when you press the R.id.finalize_entry_button to see if it is what you expect?
Also, can you post the code that hooks up the OnClick handler to your controls?

Android tableview with dynamic numbers columns and rows

This is actually a memory training app, with matrix of squares wich flips to their other side and than back to first side. And user need to click on squares that flipped. You know what I mean?
Something like that.
What I need is that sizes of the matrix would change dynamically. If user have been passed one level of complexity (matrix size is 4x4 for example), then matrix size would grow (5x5 for example), and if not then matrix size would get smaller (3x3 for example). I hope that's clear, and if not - sorry, English is not my native language =)
So if I would do it from code this would not be a problem. I would use ViewFlipper with some transition animation and create TableView with sizes that I want with inflater or something like that (or directly from code without using xml at all). And then adding it to ViewFlipper from code.
But somehow I don't like that idea.
Then next idea come into my mind. To do ViewFlipper with all possible tableviews in it and then just showNext(); or showPrevious(); depending on what user have done. But in this case XML would be of very great size.
So maybe someone knows the another way to do it?
i suggest you to look view-pager-example,
using viewflipper showNext(); or showPrevious(); you had to download all data at the same time, but using fragmen, you can load only specific data assoiated with fragment.
you can change the view on every fragment like below
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new DetailFragment();
case 1:
return new ImageFragment(R.drawable.ic_launcher);
case 2:
return new ImageFragment(R.drawable.thumb);
default:
return null;
}
}
[EDIT - For checking view in listener]
public class LoginExampleImplements extends Activity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v==btn1) {
} else if(v==btn2) {
} else if(v==btn3) {
} else if(v==btn4) {
}
}
}
[EDIT 2]
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
LinearLayout1 = (LinearLayout) findViewById(R.id.LinearLayout1);
for (int i = 0; i < 30; i++) {
button = new Button(getApplicationContext());
button.setId(i);
button.setOnClickListener(this);
LinearLayout1.addView(button);
}
}
#Override
public void onClick(View v) {
Button b = (Button)v;
b.getId()
// check clikedId
}
[EDIT 3]
public class MainActivity extends Activity implements OnClickListener{
ImageView img;
LinearLayout LinearLayout1;
LinearLayout.LayoutParams layoutParams;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout1 = (LinearLayout) findViewById(R.id.ln1);
layoutParams = new LinearLayout.LayoutParams(100, 100);
for (int i = 0; i < 30; i++) {
img = new ImageView(getApplicationContext());
img.setId(i);
img.setTag(i);
layoutParams.setMargins(10, 10, 10, 10);
img.setLayoutParams(layoutParams);
img.setBackgroundColor(Color.RED);
img.setPadding(10, 10, 10, 10);
img.setOnClickListener(this);
LinearLayout1.addView(img);
}
}
#Override
public void onClick(View v) {
ImageView b = (ImageView)v;
b.setBackgroundColor(Color.BLUE);
b.setImageLevel(Integer.valueOf(String.valueOf(b.getTag())));
}
}

Categories

Resources