I am newbie to android and trying to develop Income Tax Calculator as a part of my project. I have around 8 fields on a page and i want to sum up all those fields and display it in textview. I have written following code for that:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.TextView;
public class Tab2 extends Activity {
/** Called when the activity is first created. */
public int tot_ded=0;
public int value1=0;
public int value2=0;
public int value3=0;
public int value4=0;
public int value5=0;
public int value6=0;
public int value7=0;
public int value8=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab2);
EditText e1=(EditText)findViewById(R.id.txtHRA);
EditText e2=(EditText)findViewById(R.id.txt80C);
EditText e3=(EditText)findViewById(R.id.txthome_loan_inte);
EditText e4=(EditText)findViewById(R.id.txtmedi_ins_self);
EditText e5=(EditText)findViewById(R.id.txtmedi_ins_depe);
EditText e6=(EditText)findViewById(R.id.txtmedi_reim);
EditText e7=(EditText)findViewById(R.id.txtcon_allo);
EditText e8=(EditText)findViewById(R.id.txtprof_tax);
TextView Textv1 = (TextView)findViewById(R.id.txttotal_dedu);
//When I remove this code from comment, it stops my app.
/* value1=Integer.parseInt(e2.getText().toString());
value2=Integer.parseInt(e2.getText().toString());
value3=Integer.parseInt(e3.getText().toString());
value4=Integer.parseInt(e4.getText().toString());
value5=Integer.parseInt(e5.getText().toString());
value6=Integer.parseInt(e6.getText().toString());
value7=Integer.parseInt(e7.getText().toString());
value8=Integer.parseInt(e8.getText().toString());
tot_ded=value1+value2+value3+value4+value5+value6+value7+value8;*/
e7.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
//Textv1.setText(tot_ded);
}
}
});
}
}
Can anybody help me out. I know question is childish but I really dont know what to do. Pls help me out.
e8.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
value1=Integer.parseInt(e1.getText().toString());
value2=Integer.parseInt(e2.getText().toString());
value3=Integer.parseInt(e3.getText().toString());
value4=Integer.parseInt(e4.getText().toString());
value5=Integer.parseInt(e5.getText().toString());
value6=Integer.parseInt(e6.getText().toString());
value7=Integer.parseInt(e7.getText().toString());
value8=Integer.parseInt(e8.getText().toString());
tot_ded=value1+value2+value3+value4+value5+value6+value7+value8;
Textv1.setText(tot_ded);
}
}
});
You first need to add a button to sum up all the edit texts.
Set InputType of every edittext to number likeandroid:inputType="number"
3.on button click check for every edittext for empty value like
if(et1.getText().toString.equals("")||et2.getText().toString.equals("")||et3.getText().toString.equals(""))
{
Toast.makeText("No value should be empty");
}
else
{
value1=Integer.parseInt(e1.getText().toString());
value2=Integer.parseInt(e2.getText().toString());
value3=Integer.parseInt(e3.getText().toString());
value4=Integer.parseInt(e4.getText().toString());
value5=Integer.parseInt(e5.getText().toString());
value6=Integer.parseInt(e6.getText().toString());
value7=Integer.parseInt(e7.getText().toString());
value8=Integer.parseInt(e8.getText().toString());
tot_ded=value1+value2+value3+value4+value5+value6+value7+value8;
Textv1.setText(tot_ded);
}
Hope this will work....
if you do this
value1=Integer.parseInt(e2.getText().toString());
and all the code after that when you remove the comments you are getting absolutely nothing from the editText and you cannot
Integer.parseInt("");
it will throw a NumberFormatException
id say your best bet is to make a button and make sure all the edit texts actually have int's in them before you do your calculation
Related
I am testing the longclick and the short click features for a simple standalone project. What I am planning to do is, when I click on a button/header it will call a fragment , but when I long click viz., even without releasing my finger , I want the popup to show. My current implementation shows the popup no matter I do a long click or a short click. I would like toshow popup only upon long click and not upon short click. Also, through the popup select menu,I want to trigger a related fragment to the options selected.Is there a way to do this?Can you modify my existing code to reflect that?
Thanks!
Here's my code:
Mainactivity.java:
package com.example.longclick;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
Button btnList;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnList = (Button)this.findViewById(R.id.btnListSample);
btnList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final CharSequence[] items = {"Personal Lists", "Shared Lists"};
AlertDialog.Builder listBuilder = new AlertDialog.Builder(MainActivity.this);
listBuilder.setTitle("Manage Categories");
listBuilder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertList = listBuilder.create();
alertList.show();
}
});
}
}
and associated xml:
activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:text="Lists Header"
android:id="#+id/btnListSample"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
</Button>
</LinearLayout>
Well you should implement your own code but here are the basics
btnList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View vi) {
}
});
btnList.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
return false;
}
});
Try changing your button a text view or something else. Then for that object, add two listeners:
onLongClickListener
and
onClickListner
you could try adding the onLongClickListener to the button object but I'm not sure if that is possible or not.
you should add OnLongClickListener to the button:
btnList.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public void onLongClick(View v) {
//what you want to do
}
});
You can call start an activity from the dialog, and make fragment transaction too, but i don't understand what exactly you want to do.
I am implementing a epub reading app where I am using textview for showing text of epub. I want to select text from textview when user long presses on textview and then do multiple operations on selected text of textview like highlight etc..
So, How can I show those cursors to user to select text whatever user wants.
*I dont want to use EditText and make it look like textview. May be overriding textview is prefered.
*I have attached screenshot to explain what I am looking for-
This is asked long time ago, when I had this problem myself as well. I made a Selectable TextView myself for my own app Jade Reader. I've hosted the solution to GitHub. (The code at BitBucket ties to the application, but it's more complete and polished.)
Selectable TextView (on GitHub)
Jade Reader (on BitBucket)
Using the following code will make your TextView selectable.
package com.zyz.mobile.example;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
public class MainActivity extends Activity {
private SelectableTextView mTextView;
private int mTouchX;
private int mTouchY;
private final static int DEFAULT_SELECTION_LEN = 5;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// make sure the TextView's BufferType is Spannable, see the main.xml
mTextView = (SelectableTextView) findViewById(R.id.main_text);
mTextView.setDefaultSelectionColor(0x40FF00FF);
mTextView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
showSelectionCursors(mTouchX, mTouchY);
return true;
}
});
mTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mTextView.hideCursor();
}
});
mTextView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
mTouchX = (int) event.getX();
mTouchY = (int) event.getY();
return false;
}
});
}
private void showSelectionCursors(int x, int y) {
int start = mTextView.getPreciseOffset(x, y);
if (start > -1) {
int end = start + DEFAULT_SELECTION_LEN;
if (end >= mTextView.getText().length()) {
end = mTextView.getText().length() - 1;
}
mTextView.showSelectionControls(start, end);
}
}
}
It depends on the minimum Android version that you'd like to support.
On 3.0+, you have the textIsSelectable attribute on the TextView, which enables this behavior. E.g.:
<TextView android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="#dimen/padding_medium"
android:text="#string/hello_world"
android:bufferType="spannable"
android:textIsSelectable="true"
android:textSize="28dip"
tools:context=".MainActivity" />
Below that, you best bet is to use an EditText that looks and behaves like a TextView (apart from the slection thing). Or you can implement this feature yourself using spans.
Well... here's a problem it looks like I'm not the first to experience looking through other questions, however I can't find one that's Android-specific (others are C++ or straight java with different scenarios).
I have a calculator that determines your fuel mileage needs with given user inputs. The thing I'm adding now is a "burnoff" aspect where you can calculate the weight lost over the course of the race. Before adding the weight/burnoff element, everything worked fine.
Now, everything calculates normally except the weight on the first click.
On the second click (and subsequent clicks) it calculates properly. I suspect it has something to do with the switch statement and its location, but I could be wrong.... and even if I'm not, I'm not sure how to change it.
Looking for help on getting it all functioning properly on the first click. Thanks!
EDIT: The non-exception Toast text I put in as a debugger to determine if it was a math issue or what in the code. It pops up with "0.0" on the first click, then either "6.2" or "6.6" on subsequent clicks.
package com.tomcat.performance;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class Fuelsimple extends Activity implements OnCheckedChangeListener{
double fuelweight;
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch (checkedId){
case R.id.rbMethanol:
fuelweight = 6.6;
break;
case R.id.rbGasoline:
fuelweight = 6.2;
break;}
}
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.fuelsimple);
RadioGroup rgFuelType = ((RadioGroup) findViewById (R.id.rgFuelType));
rgFuelType.setOnCheckedChangeListener(this);
RadioButton rbMethanol = ((RadioButton) findViewById(R.id.rbMethanol));
RadioButton rbGasoline = ((RadioButton) findViewById(R.id.rbGasoline));
Button gen = ((Button) findViewById(R.id.submit));
gen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
EditText fuelUsed, pracLaps, featureLaps;
pracLaps = ((EditText) findViewById(R.id.pracLaps));
fuelUsed = ((EditText) findViewById(R.id.fuelUsed));
featureLaps = ((EditText) findViewById(R.id.featureLaps));
TextView textLPGValue, textFuelNeededValue, textBurnoffValue;
try{
double pracLapsVar = Double.parseDouble(pracLaps.getText().toString());
double fuelUsedVar = Double.parseDouble(fuelUsed.getText().toString());
double featureLapsVar = Double.parseDouble(featureLaps.getText().toString());
double efficiency = (pracLapsVar / fuelUsedVar);
double fuelNeeded = (featureLapsVar / efficiency);
double burnoff = (1.05 * (fuelNeeded * fuelweight));
Toast andJelly = Toast.makeText(Fuelsimple.this, String.valueOf(fuelweight), Toast.LENGTH_LONG);
andJelly.show();
textLPGValue = ((TextView) findViewById(R.id.textLPGValue));
textFuelNeededValue = ((TextView) findViewById(R.id.textFuelNeededValue));
textBurnoffValue = ((TextView) findViewById(R.id.textBurnoffValue));
textLPGValue.setText(String.valueOf(String.format("%.3f", efficiency)) + " laps per gallon");
textFuelNeededValue.setText(String.valueOf(String.format("%.3f", fuelNeeded)) + " gallons");
textBurnoffValue.setText(String.valueOf(String.format("%.2f", burnoff)) + " pounds");
} catch (NumberFormatException e) {Toast andEggs = Toast.makeText(Fuelsimple.this, "Please complete all fields and enter your fuel & lap info in decimals or whole numbers.", Toast.LENGTH_LONG); andEggs.show();}
catch (NullPointerException n) {Toast andEggs = Toast.makeText(Fuelsimple.this, "Please enter ALL lap and fuel data.", Toast.LENGTH_LONG);
andEggs.show();}
}}
);
}
public void onClick(View v) {
}
}
As far as I can tell, your variable fuelWeight is never initialized until a radio button is pressed. The simplest way to fix this would be to call setChecked(true) on either rbmethanol or rbGasoline after setting the listener, maybe right below where you initialize those variables. Doing it after setting the listener is important, because you want the switch statement to be resolved. Right now, before you press a radio button, fuelWeight, as with all numeric primitive data types, will be initialized to 0. This is probably the reason your first calculations are wrong.
You can also have a look at CheckChangeListener.It is called whenever the check state changes.
cbSave.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int visibility = isChecked ? View.VISIBLE : View.GONE;
findViewById(R.id.nameInstructions).setVisibility(visibility);
findViewById(R.id.name).setVisibility(visibility);
}
I have to design an xml file in which the color of the text on the Editfield is grey as the application runs on the emulator.But while entering the values into that field I want the values which will be entered by me,to be black in color.How to do this? Say for Example:
<EditText android:text="minuten"
android:textColor="#C0C0C0"
android:layout_height="wrap_content"
android:id="#+id/editText2"
android:layout_width="300dip">
</EditText>
Here the color is #C0C0C0(grey),while entering the values on my emulator into the screen,the values should appear black in color.
I don't know if there is a way to do that trought xml, but you can change the color of the text inside your edit text dinamically, using the focus!
You can set a FocusChangeListener, that way when the edit text is focused, you can make the text black, when its not focused, it goes back to gray.
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
public class Q7035767 extends Activity {
/** Called when the activity is first created. */
EditText et1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et1 = (EditText) findViewById(R.id.editText1);
et1.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus)
et1.setTextColor(Color.BLACK);
else
et1.setTextColor(Color.GRAY);
}
});
}
}
i think android:textColor will solve your problem
reference:http://developer.android.com/reference/android/widget/TextView.html
I want to show all my validation error's of EdiText fields in a popup as shown in below image:
As far as I know Android has drawables:
1) popup_inline_error.9.png
2) popup_inline_error_above.9.png
3) indicator_input_error.png
I am able to display the red error indicator inside the right side of the EditText by using:
Drawable err_indiactor = getResources().getDrawable(R.drawable.indicator_input_error);
mEdiText.setCompoundDrawablesWithIntrinsicBounds(null, null, err_indiactor, null);
Now also i want to display the error message as shown is the first image but it seems I am not getting any idea about this, though I think it should be a Custom Toast.
As the earlier answer is solution for my problem but I have tried a different approach to use a custom Drawable image instead of default indicator_input_error image.
Default Drawable
Custom Drawable
So, I have just created two EditText in my layout xml file and then implemented some Listener in Java code on that EditText.
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:padding="20dip"
android:background="#222222">
<EditText android:layout_width="match_parent"
android:layout_height="wrap_content" android:hint="Username"
android:id="#+id/etUsername" android:singleLine="true"
android:imeActionLabel="Next"></EditText>
<EditText android:layout_width="match_parent"
android:inputType="textPassword"
android:layout_height="wrap_content" android:hint="Password"
android:id="#+id/etPassword" android:singleLine="true"
android:imeActionLabel="Next"></EditText>
</LinearLayout>
EditTextValidator.java
import java.util.regex.Pattern;
import android.app.Activity;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class EditTextValidator extends Activity {
private EditText mUsername, mPassword;
private Drawable error_indicator;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Setting custom drawable instead of red error indicator,
error_indicator = getResources().getDrawable(R.drawable.emo_im_yelling);
int left = 0;
int top = 0;
int right = error_indicator.getIntrinsicHeight();
int bottom = error_indicator.getIntrinsicWidth();
error_indicator.setBounds(new Rect(left, top, right, bottom));
mUsername = (EditText) findViewById(R.id.etUsername);
mPassword = (EditText) findViewById(R.id.etPassword);
// Called when user type in EditText
mUsername.addTextChangedListener(new InputValidator(mUsername));
mPassword.addTextChangedListener(new InputValidator(mPassword));
// Called when an action is performed on the EditText
mUsername.setOnEditorActionListener(new EmptyTextListener(mUsername));
mPassword.setOnEditorActionListener(new EmptyTextListener(mPassword));
}
private class InputValidator implements TextWatcher {
private EditText et;
private InputValidator(EditText editText) {
this.et = editText;
}
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (s.length() != 0) {
switch (et.getId()) {
case R.id.etUsername: {
if (!Pattern.matches("^[a-z]{1,16}$", s)) {
et.setError("Oops! Username must have only a-z");
}
}
break;
case R.id.etPassword: {
if (!Pattern.matches("^[a-zA-Z]{1,16}$", s)) {
et.setError("Oops! Password must have only a-z and A-Z");
}
}
break;
}
}
}
}
private class EmptyTextListener implements OnEditorActionListener {
private EditText et;
public EmptyTextListener(EditText editText) {
this.et = editText;
}
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_NEXT) {
// Called when user press Next button on the soft keyboard
if (et.getText().toString().equals(""))
et.setError("Oops! empty.", error_indicator);
}
return false;
}
}
}
Now I have tested it like:
For empty EditText validations :
Suppose user click on the Username field then Softkeybord opens and if user press Next key then the user will be focused to the Password field and Username field remains empty then the error will be shown like as given in below images:
For wrong input validations :
1) I type the text vikaS in Username field then error will be like as given in below image :
2) I type the text Password1 in password field then error will be like as given in below image :
Note:
Here I have used custom drawable only in case of when user left the EditText field blank and press Next key on key board but you can use it in any case. Only you need to supply Drawable object in setError() method.
try this..
final EditText editText=(EditText) findViewById(R.id.edit);
editText.setImeActionLabel("",EditorInfo.IME_ACTION_NEXT);
editText.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId==EditorInfo.IME_ACTION_NEXT){
if( editText.getText().toString().trim().equalsIgnoreCase(""))
editText.setError("Please enter some thing!!!");
else
Toast.makeText(getApplicationContext(),"Notnull",Toast.LENGTH_SHORT).show();
}
return false;
}
});
I know answer has been accepted by the asker, but none of the above worked for me.
I was able to reproduce this on my Nexus S running Android 4.0.3.
Here's how I made it work.
Create a theme with:
<style name="MyApp.Theme.Light.NoTitleBar" parent="#android:style/Theme.Light.NoTitleBar">
<item name="android:textColorPrimaryInverse">#android:color/primary_text_light
</item>
</style>
Apply MyApp.Theme.Light.NoTitleBar theme to my application / activity from manifest.
<application
android:name=".MyApp"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/MyApp.Theme.Light.NoTitleBar"
>