Alignment Layout exchange between classes - Android Studio - android

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.

Related

How to edit and get the updates of the editText input fields from another activity?

I'm trying to play around with two activities. Edit and View activity. I would like to get the inputs from the edit activity and show in the view activity. In the edit activity I have the ok/submit button, which approves the changes and take back to the view activity, in this case the input text fields should be updated with the entered data. If the cancel button is pressed, then obviously no changes being done and the user is being taken back to the view activity.
I've most of the implementations done right, but I can't get the entered data to be shown on the view activity. What am I missing?
This is my codes for edit and view activities.
ViewActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class ViewActivity extends AppCompatActivity {
public static final String EXTRA_FNAME = "EXTRA_TEXT";
public static final String EXTRA_LNAME = "EXTRA_TEXT";
public static final String EXTRA_EMAIL = "EXTRA_TEXT";
String Fname, Lname, email;
EditText FNInput, LNInput, emailInput;
Button editButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
FNInput = (EditText) findViewById(R.id.FNInput);
LNInput = (EditText) findViewById(R.id.LNInput);
emailInput = (EditText) findViewById(R.id.emailInput);
editButton = (Button) findViewById(R.id.okButton);
editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openEditActivity();
}
});
Fname = FNInput.getText().toString();
Lname = LNInput.getText().toString();
email = emailInput.getText().toString();
}
public void openEditActivity(){
Intent intent = new Intent(this, EditActivity.class);
intent.putExtra(EXTRA_FNAME, Fname);
intent.putExtra(EXTRA_LNAME, Lname);
intent.putExtra(EXTRA_EMAIL, email);
startActivity(intent);
}
}
EditActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class EditActivity extends AppCompatActivity {
public static final String EXTRA_FNAME = "EXTRA_TEXT";
public static final String EXTRA_LNAME = "EXTRA_TEXT";
public static final String EXTRA_EMAIL = "EXTRA_TEXT";
String Fname, Lname, email;
EditText FNInput, LNInput, emailInput;
Button okButton, cancelButton;
private static final String TAG = "EditActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
FNInput = (EditText) findViewById(R.id.FNInput);
LNInput = (EditText) findViewById(R.id.LNInput);
emailInput = (EditText) findViewById(R.id.emailInput);
okButton = (Button) findViewById(R.id.okButton);
cancelButton = (Button) findViewById(R.id.cancelButton);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateViewActivity();
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FNInput.setText("");
LNInput.setText("");
emailInput.setText("");
finish();
}
});
}
public void updateViewActivity(){
Fname = FNInput.getText().toString();
Lname = LNInput.getText().toString();
email = emailInput.getText().toString();
FNInput.setText(Fname);
LNInput.setText(Lname);
emailInput.setText(email);
Intent intent = new Intent(this, ViewActivity.class);
intent.putExtra(EXTRA_FNAME, Fname);
intent.putExtra(EXTRA_LNAME, Lname);
intent.putExtra(EXTRA_EMAIL, email);
startActivity(intent);
}
}
activity_view.xml
<RelativeLayout 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=".ViewActivity">
<LinearLayout
android:layout_width="270dp"
android:layout_height="374dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="57dp"
android:layout_marginTop="75dp"
android:orientation="vertical">
<EditText
android:id="#+id/FNInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="First Name"
android:inputType="textPersonName" />
<EditText
android:id="#+id/LNInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Last Name"
android:inputType="textPersonName" />
<EditText
android:id="#+id/emailInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="info#mail.com"
android:inputType="textEmailAddress" />
<Button
android:id="#+id/okButton"
android:layout_width="153dp"
android:layout_height="wrap_content"
android:text="Edit" />
</LinearLayout>
<TextView
android:id="#+id/viewTV"
android:layout_width="134dp"
android:layout_height="33dp"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginEnd="135dp"
android:layout_marginBottom="18dp"
android:text="View Activity"
tools:layout_editor_absoluteX="15dp"
tools:layout_editor_absoluteY="687dp" />
</RelativeLayout>
activity_edit.xml
<RelativeLayout 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=".EditActivity">
<LinearLayout
android:layout_width="270dp"
android:layout_height="374dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="57dp"
android:layout_marginTop="75dp"
android:orientation="vertical">
<EditText
android:id="#+id/FNInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="First Name"
android:inputType="textPersonName" />
<EditText
android:id="#+id/LNInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Last Name"
android:inputType="textPersonName" />
<EditText
android:id="#+id/emailInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="info#mail.com"
android:inputType="textEmailAddress" />
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/okButton"
style="#style/Widget.AppCompat.Button.Borderless.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK"
android:textColor="#03A9F4" />
<Button
android:id="#+id/cancelButton"
style="#style/Widget.AppCompat.Button.ButtonBar.AlertDialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel"
android:textAlignment="center" />
</TableRow>
</LinearLayout>
<TextView
android:id="#+id/viewTV"
android:layout_width="108dp"
android:layout_height="38dp"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="169dp"
android:layout_marginBottom="18dp"
android:text="Edit Activity" />
</RelativeLayout>
I'm sorry this post is going to be lengthy.
When you want to do something like this, you have to follow some steps and follow them properly. which are:-
First, making yourself clear what you want to do exactly, that mean your goal.
Secondly, try to understand what you should do to achieve that goal, like - what thing might have need to do that, resources, tutorial (for this scenario) etc.
Finally let's start searching and learn how to do that.
Here, I can tell you where the problem is, you started learning but didn't completed the learning. I can see you just copied and pasted into two different activities without a reason.
Well, I am sharing what problems I found out from the above code of yours :-
Your ViewActivity.java should be consist of some TextView where you're intended to show your data from your EditActivity.java, which is not there.
You're sending Data with same key every time (another proof of copy pasting, not knowing what is happening) which is -
public static final String EXTRA_FNAME = "EXTRA_TEXT"; // use it as EXTRA_FNAME public static final String EXTRA_LNAME = "EXTRA_TEXT"; // use it as EXTRA_LNAME public static final String EXTRA_EMAIL = "EXTRA_TEXT"; // use it as EXTRA_EMAIL
When you are sending data to your view activity, you need to receive what you were sending by using getIntent() something like :- String s = getIntent().getStringExtra("EXTRA_FNAME"); which will return the value assigned to this key from your previous activity while sending to the present activity.
After receiving the desired value populate your TextView in the next line like this :- textView.setText(s); // fetched from getIntent() previously
For more information you can check this tutorial, which has showed how to pass and view data from one activity to another. Hope you understand.

TextView onClickListener crashes app when clicked on [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
findViewById returns null
(4 answers)
Null pointer Exception - findViewById()
(12 answers)
Closed 3 years ago.
I am new in android development. I'm trying to make a simple login and registration form. I have a TextView 'Sign up' which basically takes the user to the registerActivity when clicked on, but when everytime when i click on the sign up textView it crashes my app. I have searched for the solutions but i can't seem to figure out whats causing the crash.
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".LoginActivity"
android:orientation="vertical"
android:gravity="center_horizontal"
android:background="#drawable/bg"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="200dp"
android:layout_marginTop="70dp"
app:srcCompat="#drawable/logo"
/>
<EditText
android:id="#+id/edittext_username"
android:layout_width="249dp"
android:layout_height="71dp"
android:layout_marginTop="20dp"
android:drawableLeft="#drawable/user"
android:drawablePadding="10dp"
android:textColorHint="#f8f8f8"
android:paddingLeft="15dp"
android:hint="#string/mobile"
android:textColor="#f8f8f8"
android:background="#drawable/rounded_edittext" />
<EditText
android:id="#+id/edittext_password"
android:layout_width="249dp"
android:layout_height="71dp"
android:layout_marginTop="20dp"
android:drawableLeft="#drawable/password"
android:drawablePadding="10dp"
android:textColorHint="#f8f8f8"
android:paddingLeft="15dp"
android:hint="#string/password"
android:textColor="#f8f8f8"
android:background="#drawable/rounded_edittext"/>
<Button
android:id="#+id/button_login"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginTop="20dp"
android:background="#drawable/rounded_buttons"
android:text="#string/login"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="35dp"
android:text="Not Registered?"
android:textColor="#000000" />
<TextView
android:id="#+id/textview_register"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:paddingLeft="5dp"
android:textStyle="bold"
android:textColor="#e8170c"
android:text="#string/register"/>
</LinearLayout>
JAVA:
package com.example.careerhunts.raw;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class LoginActivity extends AppCompatActivity {
EditText mTextUsername;
EditText mTextPassword;
Button mButtonLogin;
TextView mTextViewRegister;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); //will hide the title
getSupportActionBar().hide(); // hide the title bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN); //enable full
screen
setContentView(R.layout.activity_login);
mTextUsername = findViewById(R.id.edittext_username);
mTextPassword = findViewById(R.id.edittext_password);
mButtonLogin = findViewById(R.id.button_login);
mTextViewRegister = findViewById(R.id.textview_register);
mTextViewRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(LoginActivity.this,
RegisterActivity.class);
startActivity(registerIntent);
}
});
}
}
I tested same code, Its's working fine, by guessing i can tell that you may misspelled name of activity_login (may be you assigned different layout which doesnot have text view named textview_register) or may be you dont have activity named RegisterActivity.class.

Can't make calculations using a mix of TextView and EditText

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.

Insert layout into another layout

i'm struggling with this problem: I want to create a "whatsapp like" list of conversations and i'd like to bundle image, username and last message in a single external layout that I can call programmatically to then add a new one, but for some reason this doesn't work.
chat_link_layout.xml
<TextView
android:text="Username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/username"
android:layout_toRightOf="#+id/profileimage"
android:layout_toEndOf="#+id/profileimage"
android:textAppearance="#android:style/TextAppearance.Material.Medium"
android:textColor="#android:color/black"
android:textStyle="normal|bold"
android:layout_marginTop="5px"/>
<TextView
android:text="Last Message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/lastmessage"
android:layout_below="#+id/username"
android:layout_toRightOf="#+id/profileimage"
android:layout_toEndOf="#+id/profileimage"
android:textAppearance="#android:style/TextAppearance.Material.Medium"
android:textColor="#android:color/black" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="#mipmap/ic_launcher"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/profileimage"
android:layout_marginRight="10px" />
part of the MainActivity.java's onCreate function where i try to call the XML layout
View chatLinkLayout = LayoutInflater.from(getApplication()).inflate(R.layout.chat_link_layout, null);
ConstraintLayout constraintLayout = (ConstraintLayout) findViewById(R.id.content_main);
constraintLayout.setBackgroundColor(Color.BLACK);
constraintLayout.addView(chatLinkLayout);
constraintLayout.addView(new CalendarView(getApplicationContext()));
the calendar is shown with no problem.
ChatLinkLayout.java
import android.content.Context;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
public class ChatLinkLayout extends FrameLayout {
private TextView username;
private TextView lastmessage;
private ImageView profileimage;
public ChatLinkLayout(Context context) {
super(context);
username = (TextView) findViewById(R.id.username);
lastmessage = (TextView) findViewById(R.id.lastmessage);
profileimage = (ImageView) findViewById(R.id.profileimage);
}
}
Does any of you have any suggestion?
Thank you.

how to clear entries from several EditTexts?

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.

Categories

Resources