I'm a beginner in Android Studio, and I want to make a C button in calc with 2 functions.
How do I do that on one tap the C button erases only one number, and on hold erase all numbers in TextView?
findViewById(R.id.btnClear).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtScreen.setText(""); // Clear the screen
// Reset all the states and flags
lastNumeric = false;
stateError = false;
lastDot = false;
You can set an onClickListener and onLongClickListener to achieve this.
cButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String currentText = textView.getText().toString();
if(currentText.length >= 2){
currentText = currentText.substring(0, currentText.length - 2);
}else{
currentText = "";
}
textView.setText(currentText);
}
});
cButton.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
textView.setText("");
return true;
}
});
Have you looked in to the onClick() and onLongPress() methods?
cancelButton.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
myTextView.setText("");
return true;
}
});
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
removeOneCharacter();
}
});
private void removeOneCharacter()
{
String textViewValue = myTextView.getText().toString();
if (textViewValue != null && textViewValue.length >= 2)
{
myTextView.setText(textViewValue.substring(0, textViewValue.length() - 2);
}
}
The onClick() method removes on char from the TextView at a time. The onClick() method however removes the entire String from the TextView but only considering if there is already 2 or more characters to prevent an Exception from occurring due to the upper-bound of the substring.
An improvement here could be to add another if function that checks the character length within the Long press and performs a clear if there is only one character remaining.
Related
I'm trying to add a new food with some add ons, basically everytime the add field button is press it will create two edittext which is the name and price of the add on, there will be a scenario whereby users wants to delete the edittext name and price. I've successfully created two edittexts also setting them with the IDs that i'm giving them in integer. But I'm having problem with deleting the two edittext with a button whenever i click the delete field button.
// Add On
addOnLayout.removeAllViews();
addFields.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddOnCounters++;
etFoodName = new EditText(addfoodAddOn.this);
etFoodName.setId(ETFoodID);
etFoodName.setHint("Enter your AddOn Name");
etPrice = new EditText(addfoodAddOn.this);
etPrice.setId(ETPriceID);
etPrice.setHint("Enter your AddOn Price");
Log.d("-------","-------------------what is edittext name id " + ETFoodID);
Log.d("-------","-------------------what is edittext price id " + ETPriceID);
ETFoodID++;
ETPriceID++;
addOnLayout.addView(etFoodName);
addOnLayout.addView(etPrice);
}
});
removeFields.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(AddOnCounters>=1 && ETFoodID > 0 && ETPriceID > 10){
addOnLayout.removeViewAt(ETFoodID);
addOnLayout.removeViewAt(ETPriceID);
ETFoodID--;
ETPriceID--;
}
}
});
I'm expecting the result to be whenever i click the delete field button, it will delete the very bottom last two edittexts which is the name and price.
Replace your listener
removeFields.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(AddOnCounters>=1 && ETFoodID > 0 && ETPriceID > 10){
View v1 = addOnLayout.findViewById(ETFoodID);
View v2 = addOnLayout.findViewById(ETPriceID);
addOnLayout.removeView(v1);
addOnLayout.removeView(v2);
ETFoodID--;
ETPriceID--;
}
}
});
After the button click just do this:
addFields.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
etPrice.setText("")
etFoodName.setText("");
}
}
Remove it from its parent.
removeFields.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removeFromParent(etFoodName);
removeFromParent(etPrice);
}
});
static void removeFromParent(View view) {
((ViewGroup)view.getParent()).removeView(view);
}
I have around 5 edittexts.When i click submit button,it has to check whether all fields are entered or not.Along with it if any value is not entered,the focus has to go to that desired edittext.If there are many editexts empty,then the focus has to go in top down order.I have used seterror method but when i type in that editext the error msg is not going.After entering values the focus is not going to the next edittext.how to solve this issue?
caseno,dateloss,policy_rep,reg_book,Dri_lic are the different editexts used.I have written code for one editext below
caseno.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasfocus)
{
if(!hasfocus && caseno.getText().length()==0)
{
new Handler().postDelayed(new Runnable()
{
#Override
public void run() {
//ev2.clearFocus();
dateloss.clearFocus();
policy_rep.clearFocus();
reg_book.clearFocus();
Dri_lic.clearFocus();
caseno.requestFocus();
caseno.setError("Enter this field");
}
}, 100);
}
}
});
btnsubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(caseno!=null||dateloss!=null||policy_rep!=null||reg_book!=null||Dri_lic!=null)
{
Send_reportclaim_Async reportsync=new Send_reportclaim_Async();
reportsync.execute();
}
}
});
Android provides a setError() method for this:
if(edttxtDescription.getText().toString().trim().equals(""))
{
edttxtDescription.setError("Please provide description");
}
Define a method to check whether your EditTexts have valid data:
private boolean validateEditTexts()
{
boolean valid = true;
if(edttxtDescription.getText().toString().trim().equals(""))
{
edttxtDescription.setError("Please provide description");
valid = false;
}
// Similarly check all your EditTexts here and set the value of valid
......
......
return valid;
}
To validate all your EditTexts, call validateEditTexts() which will return true or false accordingly.
btnsubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(validateEditTexts()){
Send_reportclaim_Async reportsync=new Send_reportclaim_Async();
reportsync.execute();
}
}
});
Try this. This will work.
Check this:
for(EditText edit : editTextList){
if(TextUtils.isEmpty(edit.getText()){
// EditText is empty
}
}
Maintain array of EditText references: Like
EditText[] allEts = { caseno, dateloss, policy_rep, reg_book, Dri_lic };
Write the below code in onClick of submit button:
for (EditText editText : allEts) {
String text = editText.getText().toString();
if (text.length() == 0) {
editText.setError("enter this field");
editText.requestFocus();
break;
}
}
And, implement addTextChangedListener for all edittexts to clear the error after entering the text.
caseno.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
Editable text = caseno.getText();
if (caseno.getError() != null && text != null
&& text.length() > 0) {
caseno.setError(null);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
Use this on your button click
if(!textView1.toString().isEmpty() && !textView2.toString().isEmpty() && ...)
{
............
}
1) create this method
public static boolean isNullOrEmpty(String input) {
return input == null || input.isEmpty();
}
2) send data to it for validation
boolean answer = isNullOrEmpty(editText.gettext().toString());
btnsubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(TextUtils.isEmpty(caseno.getText().toString()))
{
caseno.requestFocus();
Toast.makeText(getApplicationContext(),"Enter the required fields", Toast.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(dateloss.getText().toString()))
{
dateloss.requestFocus();
Toast.makeText(getApplicationContext(),"Enter the required fields", Toast.LENGTH_LONG).show();
return;
}
}
Currently this setup is working for me...Thnks those who answered
How can i change background color of my layout by clicking on a Button ?
This is my code :
Button color_change;
LinearLayout layout;
int value = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
color_change = (Button)findViewById(R.id.color_btn);
layout = (LinearLayout)findViewById(R.id.LL);
color_change.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (value == 1) {
layout.setBackgroundColor(Color.RED);
}
else if (value == 2) {
layout.setBackgroundColor(Color.BLUE);
}
else if (value == 3) {
layout.setBackgroundColor(Color.MAGENTA);
}
else if (value == 4) {
layout.setBackgroundColor(Color.DKGRAY);
value = 0;
}
value++;
}
});
But i want replace if else condition with other code , because this code is complex and i want short code.
So any one suggest me, how can i short my code ?
You can try this
put all color into a array and in onclick method get particular color from the array and set it like
int color[]=new int[]{Color.BLUE,Color.RED,Color.GRAY};
color_change.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (value <color.length) {
layout.setBackgroundColor(color[value]);
}
value++;
}
});
There is no magic. Use the switch instead of else ifs. For the added clarity, you might consider having constants or something as values to value, so that you don't have to deal with hard-coded integers.
You could use an array to store the data:
int[] colors = {Color.RED, Color.BLUE, Color.BLACK};
int index = value % colors.length;
layout.setBackgroundColor(colors[index]);
value++;
You will use like this...
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
switch(value)
{
case 1:layout.setBackgroundColor(Color.RED);
break;
case 2:layout.setBackgroundColor(Color.BLUE);
break;
case 3: layout.setBackgroundColor(Color.MAGENTA);
break;
case 4:layout.setBackgroundColor(Color.DKGRAY);
value = 0;
break;
}
value++;
}
});
A list of colors you want to use
List<int> colorsList = new List<int>();
colorsList.add(Color.RED);
colorsList.add(Color.WHITE);
colorsList.add(Color.BLUE);
colorsList.add(Color.GREEN);
//here you can add other colors to list
Iterator<int> colorIterator = colorsList.iterator();
function to get next color
int getNextColor()
{
if(colorIterator.hasNext())
{
return colorIterator.next();
}
else
{
colorIterator = colorsList.iterator();
return colorIterator.next();
}
}
and here is your listener
color_change.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int color = getNextColor();
layout.setBackgroundColor(color);
}
});
I'm new to android development..
I have this code in my main class:
Button prevBtn, pauseBtn, nextBtn;
EditText counterTxt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_affirmations);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prevBtn = (Button)findViewById(R.id.prevBtn);
pauseBtn = (Button)findViewById(R.id.pauseBtn);
nextBtn = (Button)findViewById(R.id.nextBtn);
counterTxt = (EditText)findViewById(R.id.counterTxt);
prevBtn.setOnClickListener(new View.OnClickListener() {
int t = Integer.parseInt(counterTxt.getText().toString());
public void onClick(View v) {
counterTxt.setText(String.valueOf(t-1));
}
});
nextBtn.setOnClickListener(new View.OnClickListener() {
int t = Integer.parseInt(counterTxt.getText().toString());
public void onClick(View v) {
counterTxt.setText(String.valueOf(t+1));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_affirmations, menu);
return true;
}
When I click "Previous", the text field value becomes 19.
When I click "Next", the text field value becomes 21.
But it only displays these two values, nothing else, no matter if i click again. I want to subtract or add 1 whenever i click the appropriate buttons.
I think this happens because the event Listeners are inside onCreate() method? Any idea on how to make it update each time I click?
You need to move your parseInt inside your onClick:
nextBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int t = Integer.parseInt(counterTxt.getText().toString());
counterTxt.setText(String.valueOf(t+1));
}
});
In both cases, t is defined as a member variable of the listener, and never changed. move it inside the onClick method instead, like this (in both cases):
public void onClick(View v) {
int t = Integer.parseInt(counterTxt.getText().toString());
counterTxt.setText(String.valueOf(t-1));
}
How to change the android button after 2 clicks ?
the first time to change button i will use this code
{
public void onClick(View v) {
b.setBackgroundDrawable(getResources().getDrawable(R.drawable.menubuttonpressed));
}
}
I want to change the button view again after pressing it one more time
how can i do that ?
Perhaps do it like this:
int count = 0;
public void onClick(View v) {
count++;
if(count == 2){
count = 0;
b.setBackgroundDrawable(getResources()
.getDrawable(R.drawable.menubuttonpressed));
}
}
This will set the background after every 2nd click on your button (view).
private int clickCount =0;
public void onClick(View v) {
if (clickCount==0) {
b.setBackgroundDrawable(getResources().getDrawable(R.drawable.menubuttonpressed));
} else {
// do something else
}
clickCount++;
}
Well, one way is to keep a counter.
numberOfClicks = 0;
...
public void onClick(View v) {
...
if(numberOfClicks==0)
b.setBackgroundDrawable(getResources().getDrawable(R.drawable.menubuttonpressed0));
else if(numberofClicks==1)
b.setBackgroundDrawable(getResources().getDrawable(R.drawable.menubuttonpressed1));
...
numberofClicks++;
}