Developing my first Android calculator application, I succeeded in updating a TextView in a new activity by passing the answer via an intent, but this requires the user to hit Back to perform another calculation. I'm trying to make the doCalculation button update a simple TextView in the MainActivity and getting the error:
06-22 11:08:17.318: E/AndroidRuntime(31328): Caused by: java.lang.ClassCastException: android.widget.Button cannot be cast to android.widget.EditText
Here's my code:
/** Called when the user clicks the Calculate! button */
public void doCalculation(View view) {
// Do something in response to button
int answerInt;
String answer;
EditText numberOne = (EditText) findViewById(R.id.number1);
EditText numberTwo = (EditText) findViewById(R.id.number2);
int numberOnee = Integer.parseInt(numberOne.getText().toString());
int numberTwoo = Integer.parseInt(numberTwo.getText().toString());
answerInt = numberOnee * numberTwoo;
answer = Integer.toString(answerInt);
TextView homeAnswerView = (TextView) findViewById(R.id.homeAnswerView);
homeAnswerView.setTextSize(40);
homeAnswerView.setText(answer);
}
For reference, here's the code that worked successfully launching a new activity:
// Called when the user clicks the Calculate! button
public void doCalculation(View view) {
// Do something in response to button
int answerInt;
String answer;
Intent intent = new Intent(this, DisplayCalculationActivity.class);
EditText numberOne = (EditText) findViewById(R.id.number1);
EditText numberTwo = (EditText) findViewById(R.id.number2);
int numberOnee = Integer.parseInt(numberOne.getText().toString());
int numberTwoo = Integer.parseInt(numberTwo.getText().toString());
answerInt = numberOnee * numberTwoo;
answer = Integer.toString(answerInt);
intent.putExtra(EXTRA_MESSAGE, answer);
startActivity(intent);
}
UPDATE, the XML for reference:
<EditText
android:id="#+id/number2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView3"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:ems="10"
android:inputType="number" />
<EditText
android:id="#+id/number1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:ems="10"
android:inputType="number"
android:singleLine="true" />
<Button
android:id="#+id/calculateBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/number2"
android:layout_alignRight="#+id/number2"
android:layout_below="#+id/number2"
android:layout_marginTop="14dp"
android:onClick="doCalculation"
android:text="Calculate!" />
Thank you for your help,
-Michael
It seems like either R.id.number1 or R.id.number2 is a Button. Check your XML and make sure it's an EditText.
Edit: Original answer didn't work, but cleaning the project solved the problem.
I've just had this problem. It seems that the xml layout file is not compiled properly. Or rather it is not included in the list of changed files to be compiled.
i was having the same situation but i found out that there are two textviews with same ids in different activities so i changed one of them and the program ran clearly so check the ids of all your edittext and buttons and change the samilier even if they were in other activities and i think it will run with out any problems
I followed the steps in the answer (cleaned and then made sure it's the id) and noticed that going to the source of my EditText R.id brings me to the EditText. Thought this is definitely not a IDE cache problem.
What I did do is to change the LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
to
android:layout_width="match_parent"
android:layout_height="match_parent"
For some reason it fixed the issue (I had this whole layout wrapped in something else that I just recently removed).
Related
Click on the button event.
public void onClick(View view) {
Button result = view.findViewById(view.getId());
textNo[R.id.t1].setText("2");
Toast.makeText(getActivity(),"클릭 : " + result.getText().toString(),Toast.LENGTH_SHORT).show();
}
For example, is there a way to change the value of the first text view by clicking the first button?
There are countless buttons, so I gave resource id to each button and text
Now, for example, only 5 buttons and text views are given.
for (i = 0; i < 5; i++) {
String textId = "t" + (i + 1);
String buttonId = "b" + (i + 1);
textNo[i] = view.findViewById(getResources().getIdentifier(textId, "id", getActivity().getPackageName()));
buttonNo[i] = view.findViewById(getResources().getIdentifier(buttonId, "id", getActivity().getPackageName()));
When I press the button on the same line, I want to increase the number of text views located on it, but I kept trying, but I couldn't figure out how to do it in the fragment.
enter image description here
The outline of the XML code is as follows.
<TextView
android:id="#+id/t1"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_weight="1"
android:gravity="center"
android:text="#string/zero" />
<Button
android:id="#+id/b1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/button"
android:layout_weight="1"
android:text="#string/Click"
style="?android:attr/buttonBarButtonStyle" />
It's my first time asking this question, so I'm very inexperienced, but if you tell me, I'll try harder.
I'm sorry that I'm not good at English.
b1.setOnClickListener {
t1.text = "tttt"
}
If u have only a few buttons, you can write them in xml. For more, use horizontal RecyclerView.
You should use RecyclerView in this case. Your method isn'n correct
I am trying to clear the text in my edit text field but for some reason it is not working.
I have declared an edit text field in the xml of my view:
<EditText
android:id="#+id/enterGlucoseLevel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/mySimpleXYPlot"
android:layout_centerHorizontal="true"
android:ems="10"
android:inputType="numberDecimal" />
I have used the attribute onClick to link my button to the enterGlucoseAction() method in my MainActivity class:
<Button
android:id="#+id/enterGlucoseButton"
android:clickable="true"
android:onClick= "enterGlucoseAction"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/enterGlucoseLevel"
android:layout_centerHorizontal="true"
android:text="#string/enterGlucoseLvlButton" />
Here is that method:
public void enterGlucoseAction(View v) {
glucoseField.setText("");
Toast.makeText(v.getContext(), "You clicked the button", Toast.LENGTH_SHORT).show();
}
I get the toast pop up but my edit text field is not being cleared.
Here is my on create and instance variables in case the problem lies there.
private XYPlot plot;
private Button addGlucoseLevel;
private EditText glucoseField;
private XYSeries currentSeries;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addGlucoseLevel = (Button) findViewById(R.id.enterGlucoseButton);
glucoseField = (EditText) findViewById(R.id.enterGlucoseLevel);
currentSeries = new SimpleXYSeries(Arrays.asList(new Number[] { 7200, 8, 54000, 2, 64800, 4 }),
SimpleXYSeries.ArrayFormat.XY_VALS_INTERLEAVED,
"Glucose Level");
//Create an series of numbers to plot.
createGraph(currentSeries);
}
Thanks in advance.
And sorry, I know this has been asked before but I can't find a solution to my problem specifically.
To clear your EditText which accepts numbers use clear() method:
glucoseField.getText().clear();
You can try setting it this way:
((EditText)findViewById(R.id.enterGlucoseLevel)).getText().clear();
Alternatively you can use getText().clear(); just replace glucoseField.setText(""); with glucoseField.getText().clear();
You should use
setText("\b");
As we can use escape sequence
((EditText)findViewById(R.id.yourEditTextId)).getText().clear();
anything else crashed.
I wanted to display blinking cursor at the end of the text in TextView .
I tried by android:cursorVisible="true" in TextView But no go .
Even i tried text.setCursorVisible(true); Doesn't work .
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:cursorVisible="true"
android:textCursorDrawable="#null" />
Does any one know any solution for it ?
First of all you should use EditText in place of TextView for taking input. If still the cursor doesn't blink, set the android:cursorVisible="true"attribute in xml file, it should make the cursor blink. If your cursor is not visible in edit text, that's also a reason one can't see the cursor blinking. Set android:textCursorDrawable="#null". This should solve your problem
<EditText
android:id="#+id/editext1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textCursorDrawable="#null"
android:cursorVisible="true">
</EditText>
In your activity class, add this code as well.
EditText input = (EditText)findViewById(R.id.edittext1);
input.setSelection(input.getText().length());
There is a solution for this.
I had to do this when I was making a terminal app and I used a simple runnable put a cursor at the end and make it blink.
I made 3 class variables:
private boolean displayCursor;
private boolean cursorOn;
private String terminalText;
private TextView terminal; // The TextView Object
terminalText keeps track of the text to be displayed.
Created a class method that runs the runnable the first time
private void runCursorThread() {
Runnable runnable = new Runnable() {
public void run() {
if (displayCursor) {
if (cursorOn) {
terminal.setText(terminalText);
} else {
terminal.setText(terminalText + '_');
}
cursorOn = !cursorOn;
}
terminal.postDelayed(this, 400);
}
};
runnable.run();
}
And initiated the variables and called runCursorThread() in onCreate()
cursorOn = false;
displayCursor = true;
runCursorThread();
I think you should go for EditText. You can set its background and make it appears like TextView with below code.
Step 1
<EditText
android:id="#+id/edtText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent" >
</EditText>
Step 2
EditText edt = (EditText) findViewById(R.id.edtText);
edt.setSelection(edt.getText().length());
Output
Finally Fixed this Using the EditText as per #Chintan Rathod advice.
<EditText
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"/> //reference to #Chintan Rathod.
Code
EditText text=(EditText) findViewById(R.id.text);
text.setText("hello");
text.setSelection(text.getText().length()); // reference to #Umer Farooq code.
I know these type of question asked many time .but still nobody gave perfect answer for that.
I have question :
I want to move from EditText1 ** to another **EditText2 .
I had already detect to editText1 but how to move cursor to editText2.?
In short I had to move my cursor position from one editText1 to another EditText2 directly.
I faced this type of issue and found the solution as below.
Here I have two editText, if I press "a", my cursor will move to next step. I used below code for doing it.
final EditText editText = (EditText) findViewById(R.id.editText1);
editText.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v , int keyCode , KeyEvent event) {
EditText editText2 = (EditText) findViewById(R.id.editText2);
// TODO Auto-generated method stub
if (keyCode == event.KEYCODE_A) {
Selection.setSelection((Editable) editText2.getText(),editText.getSelectionStart());
editText2.requestFocus();
}
return true;
}
});
Let me know if you are facing any error regarding this.
For this, all you need to do is...add below two properties to your EditText tag in xml, except the last EditText(In case, you add it to the last EditText also, then the cursor control will again go to the first EditText when you press enter/next from the keypad)
<EditText
.
.
android:singleLine="true"
android:imeOptions="actionNext"
.
.
/>
Hope this helps
Here is a working example, hope this helps.
XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="#android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Some string of text"
/>
<EditText
android:id="#android:id/text2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Some string of text"
/>
<Button
android:id="#android:id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button"
/>
</LinearLayout>
Class:
public class Example extends Activity {
TextView text1;
TextView text2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text1 = (EditText) findViewById(android.R.id.text1);
text2 = (EditText) findViewById(android.R.id.text2);
Button button = (Button) findViewById(android.R.id.button1);
button.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Selection.setSelection((Editable) text2.getText(), text1.getSelectionStart());
text2.requestFocus();
}
});
}
}
Set onKeyListener to detect the key pressed on every key pressed checked your condition and when your condition will be fulfilled set edittext property edittext2.requestFocus();
I have tested all the previous code segments, and find all are working fine. But I find just calling "requestFocus()" with the proper edittext object is also working. As per as ques asked, the ans can be:
edittext2.requestFocus();
which is working fine for me. Please correct me if I am wrong.
In my app, I am creating a dialog, like so:
dialogview = inflater.inflate(R.layout.registration_dialog, null);
dialog = new AlertDialog.Builder(this);
dialog.setView(dialogview);
And then, assigning several views to variables:
username = (EditText)dialogview.findViewById(R.id.username);
password = (EditText)dialogview.findViewById(R.id.password);
confirm = (EditText)dialogview.findViewById(R.id.confirm);
rememberme = (CheckBox)dialogview.findViewById(R.id.rememberme);
autologin = (CheckBox)dialogview.findViewById(R.id.autologin);
All the variables are appropriately defined, before my onCreate:
private EditText username;
private EditText password;
private CheckBox rememberme;
private CheckBox autologin;
private EditText confirm;
When I try and create the dialog, however, the app crashes. I checked the eclipse debugger, which reports the error:
java.lang.ClassCastException: android.widget.ImageView
on the line
confirm = (EditText)dialogview.findViewById(R.id.confirm);
The XML definition for the confirm field is as follows:
<EditText android:id="#+id/confirm"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:inputType="textPassword">
</EditText>
I am beyond confused - there isn't even any ImageViews inside my dialoglayout. Is this some strange glitch? Any ideas?
The R.java file needs to be refreshed. Try to Clean your project and compile again. \