I'm currently making a very simple math game. In this math game I want the player to solve easy equations. It looks like this: 9 * __ = 45, the player then fill in the correct number to solve the equation and then presses a Correct-button. If correct scores are added to the player.
The empty space is an EditText and the others are TextViews. Because I use a mix of TextView & EditText I need somehow to make a convertion for the program to be able to read and calculate. I've been reading like crazy and tried all kinds of different methods without success. How should I do to get around this?
This is how my data looks like:
activity_play.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_play"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.android.laboration2.PlayActivity">
<TextView
android:id="#+id/textPlayMultiply"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/textPlayNumber1"
android:layout_centerHorizontal="true"
android:text="#string/multiply"
android:textAlignment="textStart"
android:layout_gravity = "start"
android:textColor="#android:color/black"
android:textSize="40sp" />
<TextView
android:id="#+id/textPlayNumber1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/textPlayScore"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/textPlayScore"
android:layout_marginTop="48dp"
android:text="#string/number_1"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="50sp" />
<TextView
android:id="#+id/textPlayEqual"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="#string/equal"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="50sp"
android:layout_below="#+id/editTextPlayNumber2"
android:layout_alignLeft="#+id/textPlayMultiply"
android:layout_alignStart="#+id/textPlayMultiply" />
<TextView
android:id="#+id/textPlayResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="29dp"
android:text="#string/result_number3"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="50sp"
android:layout_below="#+id/textPlayEqual"
android:layout_alignLeft="#+id/textPlayEqual"
android:layout_alignStart="#+id/textPlayEqual" />
<TextView
android:id="#+id/textPlayScore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="31dp"
android:layout_toStartOf="#+id/answerButton"
android:text="#string/score_0"
android:textAlignment="textStart"
android:layout_gravity="start"
android:textColor="#android:color/black"
android:textSize="24sp"
android:layout_toLeftOf="#+id/answerButton" />
<Button
android:id="#+id/answerButton"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_marginTop="36dp"
android:background="#android:color/holo_orange_dark"
android:text="#string/button_result"
android:textAllCaps="false"
android:textColor="#android:color/white"
android:textSize="18sp"
android:textStyle="bold"
android:layout_below="#+id/textPlayResult"
android:layout_centerHorizontal="true" />
<EditText
android:id="#+id/editTextPlayNumber2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textPlayMultiply"
android:layout_alignBottom="#+id/textPlayMultiply"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_toEndOf="#+id/answerButton"
android:layout_toRightOf="#+id/answerButton"
android:hint=" "
android:inputType="number"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="50sp" />
<TextView
android:id="#+id/textPlayLevel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textPlayScore"
android:layout_alignBottom="#+id/textPlayScore"
android:layout_toEndOf="#+id/answerButton"
android:layout_toRightOf="#+id/answerButton"
android:text="#string/level_0"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="24sp" />
</RelativeLayout>
.
PlayActivity.java
package com.example.android.laboration2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class PlayActivity extends AppCompatActivity implements View.OnClickListener {
TextView textPlayNumber1;
EditText editTextPlayNumber2;
TextView textPlayResult;
TextView textPlayScore;
TextView textPlayLevel;
Button answerButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
textPlayNumber1 = (TextView) findViewById(R.id.textPlayNumber1);
editTextPlayNumber2 = (EditText) findViewById(R.id.editTextPlayNumber2);
textPlayResult = (TextView) findViewById(R.id.textPlayResult);
textPlayScore = (TextView) findViewById(R.id.textPlayScore);
textPlayLevel = (TextView) findViewById(R.id.textPlayLevel);
answerButton = (Button) findViewById(R.id.answerButton);
answerButton.setOnClickListener(this);
}//onCreate ends here
#Override
public void onClick(View v) {
}//onClick ends here
}//PlayActivity ends here
You can do
int playNumberValue = Integer.getInteger(textPlayNumber1.getText().toString());
int userInputValue = Integer.getInteger(editTextPlayNumber2.getText().toString());
int result = Integer.getInteger(textPlayResult.getText().toString());
if(result == userInputValue+playNumberValue)
//win game
Your TextView and EditText all have String type values. You have to parse those value to Integer then calculate and show the result.
Here is the action onClick answer button-
int score = 0;
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.answerButton:
int playNum1 = Integer.parseInt(textPlayNumber1.getText().toString());
int playNum2 = Integer.parseInt(editTextPlayNumber2.getText().toString());
int playResult = Integer.parseInt(textPlayResult.getText().toString());
if(playNum1*playNum2 == playResult){
score++;
textPlayScore.setText(""+score);
}
break;
}
}
Hope this helps.
Related
I encountered this problem while trying to develop an android addition app and I tried to solve it by re-writing my code with making sure I don't make silly mistakes but I have no idea on how to solve it now.
I am trying to develop an android app which takes two numbers from the user and shows the sum of it, I think I am writing the correct code as their is no build errors or any problem highlighting and the app even opens but as soon as I write two numbers in the input numbers field and tap on the 'Calculate' button, my app crashes while I was expecting that the number would pop up in the TextView3.
The code of my XML file:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter 1st no:"
android:textSize="22sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.159"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.119" />
<EditText
android:id="#+id/editTextNumber2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/textView1"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.12" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter 2nd no:"
android:textSize="22sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.163"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView1"
app:layout_constraintVertical_bias="0.109" />
<EditText
android:id="#+id/editTextNumber3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.36"
app:layout_constraintStart_toEndOf="#+id/textView2"
app:layout_constraintTop_toBottomOf="#+id/editTextNumber2"
app:layout_constraintVertical_bias="0.089" />
<Button
android:id="#+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.383" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="34sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/button5"
app:layout_constraintVertical_bias="0.087" />
</androidx.constraintlayout.widget.ConstraintLayout>
The code of my Java file is:
package com.example.chapter1_futiletries;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
private Button button5;
private TextView textView1;
private TextView textView2;
private TextView textView3;
private EditText editTextNumber2;
private EditText editTextNumber3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button5 = findViewById(R.id.button5);
textView1 = findViewById(R.id.textView1);
textView2 = findViewById(R.id.textView2);
textView3 = findViewById(R.id.textView3);
editTextNumber2 = findViewById(R.id.editTextNumber2);
editTextNumber3 = findViewById(R.id.editTextNumber3);
button5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String editTextNumber2_value = editTextNumber2.getText().toString();
int num1 = Integer.parseInt(editTextNumber2_value);
String editTextNumber3_value = editTextNumber3.getText().toString();
int num2 = Integer.parseInt(editTextNumber3_value);
int finalNum = num1 + num2;
textView3.setText(finalNum);
}
});
}
}
I am using min SDK version 22 and targetSDK as 31 and I am trying to run it in the Pixel 4A and I am still learning android development so I could have made some mistakes and not understood them.
the error in line :
textView3.setText(finalNum);
because setText() should be filled always with string , As for the Integer , it is used to get String Resource , ex :
textView3.setText(R.string.appname);
The solution to your problem is :
textView3.setText(String.valueOf(finalNum));
or :
textView3.setText(""+finalNum);
I am implementing a program that uses database and interacts with different layouts of entries and editing users.
I'm working with RelativeLayout on all screens. In one of thelayouts, I insert a perfectly aligned button and give the command android:visibility="gone" for him to show upon request.
The problem is that when I need to use it at command editarBt.setVisibility(View.VISIBLE), the button appears out of alignment and overlaps the fields for entering information.
Is there any way to keep the position of command by button?
I will not put the entire code because it has 7 classes, so I'll just put the classes that interest.
EnterPatientActivity Class
package br.luizhmu.aulas_android_sqlite;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/**
* Created by LuizHMU on 2/17/15.
*/
public class EnterPatientActivity extends Activity {
private Paciente paciente = new Paciente();
private EditText nomeEt;
private EditText emailEt;
private EditText senhaEt;
private Button salvarBt;
private Button editarBt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inserir_paciente);
nomeEt = (EditText) findViewById(R.id.editTextNome);
emailEt = (EditText) findViewById(R.id.editTextEmail);
senhaEt = (EditText) findViewById(R.id.editTextSenha);
salvarBt = (Button) findViewById(R.id.buttonSalvar);
editarBt = (Button) findViewById(R.id.buttonEditar);
Intent intent = getIntent();
if(intent != null){
Bundle bundle = intent.getExtras();
if(bundle != null){
paciente.setId(bundle.getLong("id"));
paciente.setNome(bundle.getString("nome"));
paciente.setEmail(bundle.getString("email"));
nomeEt.setText(paciente.getNome());
emailEt.setText(paciente.getEmail());
senhaEt.setVisibility(View.GONE);
salvarBt.setVisibility(View.GONE);
editarBt.setVisibility(View.VISIBLE);
}
}
}
public void salvar(View view){
paciente.setNome(nomeEt.getText().toString());
paciente.setEmail(emailEt.getText().toString());
paciente.setSenha(senhaEt.getText().toString());
DataBase bd = new DataBase(this);
bd.inserir(paciente);
Toast.makeText(this, "Paciente inserido com sucesso!", Toast.LENGTH_SHORT).show();
}
public void editar(View view){
paciente.setNome(nomeEt.getText().toString());
paciente.setEmail(emailEt.getText().toString());
DataBase bd = new DataBase(this);
bd.atualizar(paciente);
Toast.makeText(this, "Paciente \""+paciente.getNome()+"\" atualizado com sucesso.", Toast.LENGTH_SHORT).show();
}
}
activity_inserir_paciente.xml
<?xml version="1.0" encoding="utf-8"?>
<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="15dp"
android:paddingRight="15dp"
android:background="#ffffea0a"
tools:context=".EnterPatientActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Novo paciente"
android:id="#+id/textView3"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textColor="#ff1727ff"
android:textSize="20dp"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="*Nome"
android:ems="10"
android:id="#+id/editTextNome"
android:layout_below="#+id/textView3"
android:layout_alignRight="#+id/buttonSalvar"
android:layout_alignEnd="#+id/buttonSalvar" />
<EditText
android:hint="Telefone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="phone"
android:ems="10"
android:id="#+id/editTextTelefone"
android:layout_below="#+id/editTextNome"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:hint="*E-mail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="#+id/editTextEmail"
android:layout_below="#+id/editTextTelefone"
android:layout_alignLeft="#+id/editTextTelefone"
android:layout_alignStart="#+id/editTextTelefone" />
<EditText
android:hint="*Senha"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="#+id/editTextSenha"
android:layout_below="#+id/editTextEmail"
android:layout_alignLeft="#+id/editTextEmail"
android:layout_alignStart="#+id/editTextEmail" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Salvar"
android:id="#+id/buttonSalvar"
android:onClick="salvar"
android:layout_below="#+id/textView4"
android:layout_alignRight="#+id/editTextSenha"
android:layout_alignEnd="#+id/editTextSenha" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Editar"
android:id="#+id/buttonEditar"
android:layout_alignTop="#+id/buttonSalvar"
android:layout_toLeftOf="#+id/buttonSalvar"
android:layout_toStartOf="#+id/buttonSalvar"
android:visibility="gone"
android:onClick="editar"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="* Campos de preenchimento obrigatório"
android:textColor="#000000"
android:id="#+id/textView4"
android:layout_below="#+id/editTextSenha"
android:layout_alignLeft="#+id/editTextSenha"
android:layout_alignStart="#+id/editTextSenha" />
</RelativeLayout>
In a RelativeLayout, you can prevent views from overlapping by using the layout_toLeftOf, layout_toRightOf, layout_above and layout_below attributes, which expect a view id as value.
Also, you might want to use View.INVISIBLE instead of View.GONE: The former will consider the view during layouting, but hide it. The latter will pretend the view does not exist, therefore altering your layout result.
I am new to java and android so please forgive me if i am asking to simple question.
I have an application which requires user input in two EditTexts. Those inputs are multipied and result is displayed in TextView. I would like to use "clear entries" button which would clear the content of user entries and displayed result. Is there any way to do it?
Here is an application code.
package c.example.rectangle;
import android.os.Bundle;
import android.view.View;
import android.app.Activity;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener{
EditText l;
EditText w;
TextView a;
Button b;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l = (EditText) findViewById(R.id.length);
w = (EditText) findViewById(R.id.width);
a = (TextView) findViewById(R.id.lblarea);
b = (Button) findViewById(R.id.calculate);
b.setOnClickListener(this);
}
public void onClick(View v) {
calculateRectangle(l.getText().toString(), w.getText().toString());
}
private void calculateRectangle(String clength, String cwidth){
double area = Double.parseDouble(clength)*Double.parseDouble(cwidth);
a.setText(String.valueOf(area));
}}
And here is my XML Code.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#8B4513"
android:orientation="vertical" >
<TextView
android:id="#+id/label1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:background="#2F4F4F"
android:gravity="center"
android:text="#string/rect"
android:textAppearance="?android:attr/textAppearanceMedium" />
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#8B4513"
android:orientation="horizontal" >
<TextView
android:id="#+id/label2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginTop="50dp"
android:background="#2F4F4F"
android:gravity="center"
android:text="#string/cm"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/length"
android:layout_width="110dp"
android:layout_height="21dp"
android:layout_marginLeft="40dp"
android:layout_marginTop="50dp"
android:background="#2F4F4F"
android:ems="10"
android:gravity="center"
android:hint="#string/help"
android:inputType="text" />
</LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#8B4513"
android:orientation="horizontal" >
<TextView
android:id="#+id/label3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#2F4F4F"
android:layout_marginLeft="30dp"
android:layout_marginTop="20dp"
android:text="#string/breadth"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/width"
android:layout_width="110dp"
android:layout_height="21dp"
android:layout_marginLeft="33dp"
android:layout_marginTop="20dp"
android:background="#2F4F4F"
android:inputType="text"
android:hint="#string/help"
android:ems="10"
android:gravity="center"
>
<requestFocus />
</EditText>
</LinearLayout>
<Button
android:id="#+id/calculate"
android:layout_width="fill_parent"
android:layout_marginLeft="100dip"
android:layout_marginRight="100dip"
android:layout_height="wrap_content"
android:text="#string/calculate"
android:layout_marginTop="20dp" />
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#8B4513"
android:orientation="horizontal" >
<TextView
android:id="#+id/label4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginTop="20dp"
android:background="#2F4F4F"
android:text="#string/area"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/lblarea"
android:layout_width="110dp"
android:layout_height="21dp"
android:layout_marginLeft="60dp"
android:layout_marginTop="20dp"
android:background="#2F4F4F"
android:gravity="center"/>
</LinearLayout>
<Button
android:id="#+id/clear"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="100dip"
android:layout_marginRight="100dip"
android:layout_marginTop="20dp"
android:text="#string/clear" />
</LinearLayout>
I would be very appreciate for the answer.
Why not just set both editTexts to empty when you no longer need the data in them to be displayed?
EditText.setText("");
Same thing with the TextView;
TextView.setText("");
If you are wanting to iterate through them, you can put them in a list then use a for loop to set the text to ""
List<EditText> myList = new List<EditText>();
myList.add(editText1);
Then in your clear method
for (int x = 0; x < myList.size(); x++
{
myList.get(x).setText("");
}
Why nobody seems to use the really useful android:onClick ?
<Button
...
android:text="#string/calculate"
android:onClick="calculate" />
<Button
...
android:text="#string/clear"
android:onClick="clearForm" />
With the following activity :
class MyActivity extends Activity
{
...
/**
* Calculate
* android:onClick="calculate"
*/
public void calculate(View view)
{
// Handle click on your 'Calculate' button
}
/**
* Clear form
* android:onClick="clearForm"
*/
public void clearForm(View view)
{
int[] ids = new int[]{R.id.length, R.id.width};
for(int id : ids)
{
((EditText) this.findViewById(id).)setText("");
}
}
}
This way, you do not have to care about ids and your code will be more clean than clean.
Ids should not be overused! They are great on views that can be 'changed' by the user to handle those changes (and to enjoy the onSaveInstanceState() natural behavior) but that's it!
IMO.
If you want to create a clear button, do the following.
Create a Button in your xml:
<Button
android:id="#+id/clear_button"
... you own layout prefs ...
/>
Create a listener for the button in your code:
OnClickListener clearButtonListener = new OnClickListener(){
#Override
public void onClick(View view) {
((EditText)findViewById(R.id.id_for_text_box_a)).setText("");
//...do this for all your edit texts that you want to clear
}
};
Connect the listener to the button
Button clearButton = (Button) findViewById(R.id.clear_button);
clearButton.setOnClickListener(clearButtonListener);
Alternatively, instead of finding the edit texts by id in the listener, they could be instance variables that get initialized in onCreate or wherever. I would also recommend not using one letter variable names.
Personally, I would set OnClickListeners instead of the onClick attribute in the XML. Although using the XML onClick attribute may amount to fewer lines of code, it unfortunately creates a very tight coupling of layout and functionality. I prefer to have XML for layout, and Java for functionality. Additionally, being forced to use ids amounts to requiring XML elements to have variable names, which makes for more readable layout code (what is this button? what is this checkbox for?). Another problem I see with using the onClick attribute is that it forces your methods called to be public, which doesn't really make sense for many of these methods. I prefer to understand what an Activity does functionally through reading the Java, and I would rather not have unreferenced public methods floating around in my Activities.
I am new to Android code development...I am developing a Android calculator apps and does not understand why the two EditTexts (first input and second input) cannot accept decimal places but can only input integers...Here attached as follows are the codes:
Thanks!
=============Main Activity===============================
package com.trial.jm4_calculator;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity {
private TextView output;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn1 = (Button) findViewById(R.id.button1);
btn1.setOnClickListener(btn1Listener);
output = (TextView) findViewById(R.id.lblOutput);
}
View.OnClickListener btn1Listener = new View.OnClickListener() {
public void onClick(View v) {
double opd1, opd2;
double result = 0.0;
EditText txtOpd1, txtOpd2;
RadioButton rdbAdd, rdbSubtract, rdbMultiply, rdbDivide;
CheckBox chkDivide;
txtOpd1 = (EditText) findViewById(R.id.txtOpd1);
txtOpd2 = (EditText) findViewById(R.id.txtOpd2);
opd1 = Double.parseDouble(txtOpd1.getText().toString());
opd2 = Double.parseDouble(txtOpd2.getText().toString());
rdbAdd = (RadioButton) findViewById(R.id.rdbAdd);
if (rdbAdd.isChecked()) {
result = opd1 + opd2;
}
rdbSubtract = (RadioButton) findViewById(R.id.rdbSubtract);
if (rdbSubtract.isChecked()) {
result = opd1 - opd2;
}
rdbMultiply = (RadioButton) findViewById(R.id.rdbMultiply);
if (rdbMultiply.isChecked()) {
result = opd1 * opd2;
}
rdbDivide = (RadioButton) findViewById(R.id.rdbDivide);
if (rdbDivide.isChecked()) {
result = opd1 / opd2;
}
output.setText("Answer = " + result);
}
};
}
====================Main.xml===================================
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="horizontal">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="First Input: "/>
<EditText
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:inputType="number"
android:id="#+id/txtOpd1"/>
</LinearLayout>
<RadioGroup
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="horizontal"
android:id="#+id/rdgOp">
<RadioButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="+ "
android:id="#+id/rdbAdd"/>
<RadioButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="- "
android:id="#+id/rdbSubtract"/>
<RadioButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="* "
android:id="#+id/rdbMultiply"/>
<RadioButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="/ "
android:id="#+id/rdbDivide"/>
</RadioGroup>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="horizontal">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Second Input: "/>
<EditText
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:inputType="number"
android:id="#+id/txtOpd2"/>
</LinearLayout>
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Compute"
android:id="#+id/button1"/>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/lblOutput"/>
</LinearLayout>
If you want to use Decimal Number only on your EditText
use the xml attribute android:inputType="numberDecimal" in your EditText widget your EditText declaration will be like this:
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal" />
If you want to use Signed Decimal Number than combine the two Xml attributes android:inputType="numberDecimal" and android:inputType="numberSigned". Your EditText declaration will be like this:
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal|numberSigned" >
</EditText>
Change android:inputType from "number" to "numberDecimal". See the documentation for even more options for inputType.
inputType="number" doesnt allow floats. try changing:
android:inputType="number"
to:
android:numeric="integer|decimal"
You need to change the input type of your EditText in the XML code.
Change the inputType attribute of the EditText from
android:inputType="number"
to
android:inputType="numberDecimal"
<EditText
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:inputType="numberDecimal"
android:id="#+id/txtOpd1"/>
I searched net to find the answer for my following problem. But no answer found. I myself tried several ways, but I am still a novice at Android. What I found on net related to scrolling is official documentation and examples of scrolling on http://developer.android.com, Mr. Senthilkumar's How to scroll the screen, Kakka47's ScrollView only part of the screen, darrinps A scroll view with only part of the screen scrolling, etc.
This is very common requirement as is clear from above titles. I have following screen layout as shown in figure.
The screen from top to column titles is stable. The table records, below column titles needs to scroll. I have AbsoluteLayout (I know it is deprecated but that is the only one I can use for by specific need), inside it a scrollview and inside scrollview a TableLayout.
User clicks "Add" button to add the orders received. One order in one row. As rows increase, they go beyond visible area. Therefore, I want it to scroll so user can access it. But this part is not scrolling. I have given the listing of my code. Please tell me what to do.
Code:
package com.BookOrders;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsoluteLayout;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
//import android.widget.TableRow.LayoutParams;
#SuppressWarnings("deprecation")
public class BookOrders extends Activity implements ScrollViewListener{
/** Called when the activity is first created. */
private TextView BookingDateDisplay;
private Button ChangeDate, AddRec, DeleteRec, SaveAll;
private CheckBox SelectedAll, SelectedRec;
private ObservableScrollView CustomScroller = null;
private ObservableScrollView CustomScrolled = null;
private int ChangedYear;
private int ChangedMonth;
private int ChangedDay;
public Context CurrentContext, UsedContext;
static final int DATE_DIALOG_ID = 0;
int IdGenerator = 100000;
int Number_of_Records = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
#SuppressWarnings("deprecation")
final AbsoluteLayout main = (AbsoluteLayout)findViewById(R.id.widget0);
CurrentContext = main.getContext();
//final ScrollView ScrollControl = (ScrollView)findViewById(R.id.scroller);
//final AbsoluteLayout LayerControl = (AbsoluteLayout)findViewById(R.id.FinalLayer);
// UsedContext = LayerControl.getContext();
// capture our View elements
CustomScroller = (ObservableScrollView) findViewById(R.id.scrollContainer);
BookingDateDisplay = (TextView) findViewById(R.id.BookedDate);
ChangeDate = (Button) findViewById(R.id.pickDate);
AddRec = (Button) findViewById(R.id.AddRecord);
DeleteRec = (Button) findViewById(R.id.DeleteRecord);
SaveAll = (Button) findViewById(R.id.SaveRecord);
SelectedAll = (CheckBox) findViewById(R.id.SelectAll);
// add a click listener to the button
ChangeDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
AddRec.setOnClickListener(new View.OnClickListener() {
public void onClick(View AddRecView) {
IdGenerator = IdGenerator+10;
UsedContext = AddRecView.getContext();
TableRow Tr = new TableRow(UsedContext);
for (int controls=0; controls<6; controls++) {
if (controls==0){
CheckBox RecordCheck = new CheckBox(UsedContext);
RecordCheck.setId(IdGenerator+controls);
RecordCheck.setTag("CheckBoxTag");
RecordCheck.setHeight(20);
RecordCheck.setWidth(25);
Tr.addView(RecordCheck);
}
if ((0 < controls ) && (controls<5)){
Spinner Record = new Spinner(UsedContext);
Record.setId(IdGenerator+controls);
//Record.setMinimumHeight(20);
//Record.setMinimumWidth(90);
Tr.addView(Record);
}
if (controls==5){
EditText OrderQuantity = new EditText(UsedContext);
OrderQuantity.setId(IdGenerator+controls);
//OrderQuantity.setHeight(20);
//OrderQuantity.setWidth(90);
Tr.addView(OrderQuantity);
}
}
TableLayout Orders = (TableLayout)findViewById(R.id.OrderData);
Orders.addView(Tr);
// Scrolls to line before last - why?
final ScrollView ScrollAttempt = (ScrollView) findViewById(R.id.scrollContainer);
ScrollAttempt.post(new Runnable() {
public void run() {
ScrollAttempt.fullScroll(View.FOCUS_DOWN);
}
});
Number_of_Records = Number_of_Records + 1;
}
});
// updates the date in the TextView
private void updateDisplay() {
BookingDateDisplay.setText(
new StringBuilder()
.append(ChangedDay).append("-")
.append(ChangedMonth + 1).append("-") // Month is 0 based so add 1
.append(ChangedYear).append(" "));
}
// the call back received when the user "sets" the date in the dialog
private DatePickerDialog.OnDateSetListener DateSetListener =
new DatePickerDialog.OnDateSetListener(){
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
ChangedYear = year;
ChangedMonth = monthOfYear;
ChangedDay = dayOfMonth;
updateDisplay();
}
};
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, DateSetListener, ChangedYear, ChangedMonth, ChangedDay);
}
return null;
}
public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
if(scrollView == CustomScroller) {
CustomScrolled.scrollTo(x, y);
} else if(scrollView == CustomScrolled) {
CustomScroller.scrollTo(x, y);
}
}
}
My main.xml:
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/widget0"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<!-- <ImageButton android:text="Date" android:layout_height="20px" android:layout_width="32px" android:id="#+id/BDate" android:layout_x="274dip" android:layout_y="51dip"></ImageButton> -->
<TextView
android:id="#+id/Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="81dip"
android:layout_y="10dip"
android:background="#0ff0ff"
android:gravity="center"
android:text="Order Booking"
android:textColor="#330000"
android:textSize="20sp"
android:textStyle="bold"
android:typeface="serif" >
</TextView>
<TextView
android:id="#+id/BDate_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="277dip"
android:layout_y="52dip"
android:gravity="right"
android:text="Booked on:"
android:textSize="12sp" >
</TextView>
<TextView
android:id="#+id/BookedDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="350dip"
android:layout_y="52dip"
android:text=""
android:textSize="12sp" >
</TextView>
<Button
android:id="#+id/pickDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="400dip"
android:layout_y="15dip"
android:text="Change Date"
android:textSize="10sp" >
</Button>
<View
android:layout_width="wrap_content"
android:layout_height="36dp"
android:layout_y="68dp"
android:background="#drawable/gradient" >
</View>
<Button
android:id="#+id/AddRecord"
android:layout_width="120dp"
android:layout_height="34dp"
android:layout_x="10dip"
android:layout_y="71dip"
android:text="Add"
android:textSize="10sp" >
</Button>
<Button
android:id="#+id/DeleteRecord"
android:layout_width="120dp"
android:layout_height="34dp"
android:layout_x="140dp"
android:layout_y="71dp"
android:text="Delete"
android:textSize="10sp" >
</Button>
<Button
android:id="#+id/ClearRecord"
android:layout_width="120dp"
android:layout_height="34dp"
android:layout_x="270dp"
android:layout_y="71dp"
android:text="Clear"
android:textSize="10sp" >
</Button>
<Button
android:id="#+id/SaveRecord"
android:layout_width="120dp"
android:layout_height="34dp"
android:layout_x="400dp"
android:layout_y="71dp"
android:text="Save"
android:textSize="10sp" >
</Button>
<View
android:layout_width="wrap_content"
android:layout_height="1dp"
android:layout_y="110dp"
android:background="#drawable/gradient" >
</View>
<CheckBox
android:id="#+id/SelectAll"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:layout_x="10dip"
android:layout_y="115dip"
android:text="Select All"
android:textSize="10sp" >
</CheckBox>
<TextView
android:id="#+id/Company"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="95dip"
android:layout_y="115dip"
android:background="#666666"
android:text="Company"
android:textColor="#000000"
android:textSize="12sp" >
</TextView>
<TextView
android:id="#+id/Product"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="200dip"
android:layout_y="115dip"
android:background="#666666"
android:text="Product"
android:textColor="#000000"
android:textSize="12sp" >
</TextView>
<TextView
android:id="#+id/Code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="300dip"
android:layout_y="115dip"
android:background="#666666"
android:text="Code"
android:textColor="#000000"
android:textSize="12sp" >
</TextView>
<TextView
android:id="#+id/Model"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="380dp"
android:layout_y="115dp"
android:background="#666666"
android:text="Model"
android:textColor="#000000"
android:textSize="12sp" >
</TextView>
<TextView
android:id="#+id/Quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="470dp"
android:layout_y="115dp"
android:background="#666666"
android:text="Quantity"
android:textColor="#000000"
android:textSize="12sp" >
</TextView>
<View
android:id="#+id/view1"
android:layout_width="wrap_content"
android:layout_height="1dp"
android:layout_x="0dip"
android:layout_y="134dip"
android:background="#drawable/gradient" >
</View>
<com.BookOrders.ObservableScrollView
android:id="#+id/scrollContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_x="1dp"
android:layout_y="140dp"
android:clickable="true"
android:fadeScrollbars="false"
android:fillViewport="true" >
<TableLayout
android:id="#+id/OrderData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:stretchColumns="0,1,2,3,4" />
</com.BookOrders.ObservableScrollView>
</AbsoluteLayout>
Have you tried a ScrollView? You can find more about ScrollView here
Here is an example of how to use ScrollView:
<ScrollView
android:id="#+id/coupons_details_scroll_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<!--You can nest any other views here, and they will be scrollable, but take care of views that have their own scrolling capabilities like ListView -->
</ScrollView>
Good luck with it :)
I worked out the solution for this. For those who would like to know can first go through the following link
http://blog.stylingandroid.com/archives/447
I used this logic. However, I create rows dynamically when user clicks "Add" button. The only problem is, if you use spinner you won't be able to set its height zero.
Nitin