In my app I have a button (Add) that takes the entered name, creates a TextView with that name and places the TextView in a LinearLayout. You should be able to create how many subjects (school subjects) you want, so the properties would need to be set in the Java code (correct me if I'm wrong). I have managed make it create the TextViews, but they have default settings. How can I make them like the first TextView? I haven't found any solution on this one nor on the Android Developers website.
Here's the XML for the LinearLayout and the first TextView:
<LinearLayout
android:id="#+id/subjectLayout"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:orientation="vertical"
app:layout_constraintBottom_toTopOf="#+id/entryEditText"
app:layout_constraintEnd_toStartOf="#+id/divider"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0">
<TextView
android:id="#+id/subjectMATHTextView"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginBottom="16dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Math"
android:textAlignment="center"
android:textSize="30sp"
app:layout_constraintBottom_toTopOf="#+id/entryEditText"
app:layout_constraintEnd_toStartOf="#+id/divider"
app:layout_constraintHorizontal_bias="0.49"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.259" />
</LinearLayout>
And the Java Code:
final ProgressBar subjectMATHProgressBar = (ProgressBar) findViewById(R.id.subjectMATHProgressBar);
final EditText entryEditText = (EditText) findViewById(R.id.entryEditText);
Button progressBtn = (Button) findViewById(R.id.progressBtn);
final Button addSubjectButton = (Button) findViewById(R.id.addSubjectBtn);
// For Progress Button
progressBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
if (!entryEditText.getText().toString().matches("")) {
int currentProgress = subjectMATHProgressBar.getProgress();
int toSet = currentProgress + Integer.parseInt(entryEditText.getText().toString());
subjectMATHProgressBar.setProgress(toSet);
}
} catch (Exception e){
Toast.makeText(getApplication().getBaseContext(), "Enter a number", Toast.LENGTH_SHORT).show();
}
}
});
final LinearLayout subjectLayout = (LinearLayout) findViewById(R.id.subjectLayout);
LinearLayout progressLayout= (LinearLayout) findViewById(R.id.progressLayout);
// For Add Subject Button
addSubjectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
// Important code:
TextView newTextView = new TextView(getApplication().getBaseContext());
newTextView.setText(entryEditText.getText().toString());
subjectLayout.addView(newTextView);
} catch (Exception e){
Toast.makeText(getApplication().getBaseContext(), "Enter a valid name", Toast.LENGTH_SHORT).show();
}
}
});
Thanks in advance!
That is not how it works, if i get it right u need to make a list of subjects?
For this purpose there is a special view - RecyclerView or ListView. It allows you to populate your layout with a list of data. Each data entry is responsible for different item in list.
Here you can find how it works and to use it:
https://developer.android.com/guide/topics/ui/layout/recyclerview
Related
I am creating a RecyclerView on a fragment, and there is a button in one of the viewHolder(cell). But on the emulator, nothing happened after I clicked on that button. I set break points in the code for onClickListener, it doesn't even jump into the breakpoint.
Here is how I implement the button in the layout file:
<Button
android:id="#+id/add_to_list_button"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_marginBottom="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text=""
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
Here is my code in the adapter:
Button mAddButton
mAddButton = (Button) itemView.findViewById(R.id.add_to_list_button);
mAddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("test button","testinbtn");
AddContactToList(GlobalPosition);
}
});
private static void AddContactToList(int pos) {
String list_id = mUnsubscribedList.get(pos - 2 - mSubscribedList.size()).getList_id();
apiInstance.AddContactToTheList(contact.getContactID(), list_id);
}
I had checked the resource ID, the resource ID is correct. I had cleaned the project, rebuild the project, quite and relaunch Android Studio.
Im currently working on a small project. Which has a textview, a button and a edittext. The textview is set to 1 and when the button is clicked the textview goes up by 1. I can fill the edittext with any number (including -1 for example). I need to get the value from the edittext and add it to the current value in the textview with the click of the same button. How do i do this? this sounds really easy but i cant seem to find a solution.
MainActivity
package com.example.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int numberText = 1;
EditText editTextID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textViewID = (TextView) findViewById(R.id.textViewID);
textViewID.setText("1");
}
public void changeValue(View view){
numberText+=1;
TextView textViewID = (TextView) findViewById(R.id.textViewID);
textViewID.setText(numberText+"");
}
}
Activity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="com.example.myapplication.MainActivity">
<TextView
android:id="#+id/textViewID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.238" />
<Button
android:id="#+id/PlusID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="changeValue"
android:text="#string/plus"
tools:ignore="MissingConstraints"
android:layout_marginTop="50dp"
app:layout_constraintTop_toBottomOf="#+id/textViewID"
android:layout_marginLeft="0dp"
app:layout_constraintLeft_toLeftOf="#+id/textViewID"
android:layout_marginRight="0dp"
app:layout_constraintRight_toRightOf="#+id/textViewID" />
<EditText
android:id="#+id/editTextID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:ems="10"
android:inputType="textPersonName"
app:layout_constraintTop_toBottomOf="#+id/PlusID"
android:layout_marginLeft="0dp"
app:layout_constraintLeft_toLeftOf="#+id/PlusID"
android:layout_marginRight="0dp"
app:layout_constraintRight_toRightOf="#+id/PlusID" />
</android.support.constraint.ConstraintLayout>
You can get EditText value as follows within changeValue:
EditText editTextID = (EditText ) findViewById(R.id.editTextID);
try {
int editValue = Integer.parseInt(editTextID.getText().toString());
} catch (NumberFormatException e) {
// edit text value not a valid integer
}
Then it should be simple to add editValue to numberText and display in the TextView.
Here is how:
public void changeValue(View view) {
// Retrieve the content from EditText
editTextID = (EditText) findViewById(R.id.edit_text);
String content = editTextID.toString();
// Then the value of that content
// Wrap below statement in a try-catch for a NumberFormatException
int value1 = Integer.parseInt(content);
// Add it to value from TextView
TextView textViewID = (TextView) findViewById(R.id.textViewID);
// Wrap below statement in a try-catch for a NumberFormatException
int value2 = Integer.parseInt(textViewID.toString());
// Finally set the correct value
int value = value1 + value2;
textViewID.setText(value + "");
}
Also, store the references to TextView and EditText as class fields rather than calling findViewById() again.
int currentNum=Integer.parseInt(textView.getText().toString());
int addedNum=Integer.valueOf(editText.getText().toString());
currentNum+=addedNum;
textView.setText(String.valueOf(currentNum));
Try initialising the required views first & storing the View instances... It would make your task a lot easier.
public class MainActivity extends AppCompatActivity {
private TextView displayValueTextView;
private EditText valueEditText;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews(){
displayValueTextView = (TextView) findViewById(R.id.tv_value);
valueEditText = (EditText) findViewById(R.id.et_input);
button = (Button) findViewById(R.id.button);
}
}
Here's the XML layout so you don't get confused about the Views and their associated Id's;
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/rl_activity_main"
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.myapplication.MainActivity">
<TextView
android:id="#+id/tv_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="26sp"
android:layout_centerInParent="true"
android:maxLines="1"
android:text="Hello World"/>
<EditText
android:id="#+id/et_input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:ems="9"
android:hint="#string/hint_text"
android:maxLines="1"/>
<Button
android:id="#+id/button"
android:text="#string/plus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="changeValue"
android:layout_toRightOf="#+id/et_input"
android:layout_alignBottom="#+id/et_input"/>
</RelativeLayout>
The onClick attribute of the Button is set to changeValue this is our method that will change the value of our TextView, dependent on what number is on your EditText. This method is shown below:
public void changeValue(View view) {
double numberToAdd;
double currentValue;
try {
numberToAdd = Double.parseDouble(valueEditText.getText().toString());
} catch (Exception ex) {
ex.printStackTrace();
Toast.makeText(this, "Edit Text must contain a number.", Toast.LENGTH_LONG).show();
valueEditText.setText("");
numberToAdd = 0;
}
try {
currentValue = Double.parseDouble(displayValueTextView.getText().toString());
} catch (Exception ex) {
ex.printStackTrace();
currentValue = 0;
Toast.makeText(this, "Current value is not a number. It is now set to 0.", Toast.LENGTH_LONG).show();
displayValueTextView.setText("0");
}
double finalValue = currentValue + numberToAdd;
displayValueTextView.setText(finalValue + "");
}
The numberToAdd variable is the number we are adding to our current TextView... We must;
Extract the value the EditText holds by getting it's text and parsing it as a double (this will allow us to handle decimals numbers in the EditText).
We then extract the current value of our TextView (if it is not a number an exception will be thrown and the textview will default to 0).
Finally we add the two values and set the TextView as the string representing the added values.
I have a dialog that shows an error message,
i know i can take that error message and just make it invisible, and visible in the code,
but then the Dialog would still save room in it and it will just show as a white space.
I want the error message to be added dynamical so if no error message will be shown the dialog will be sized accordingly.
how do i do that ?
here is my Dialog >
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:id="#+id/textContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:counterEnabled="true"
app:counterMaxLength="14">
<EditText
android:id="#+id/barcode_activity_input_editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:ems="10"
android:hint="Enter Serial Number"
android:inputType="number"
android:maxLength="14" />
</android.support.design.widget.TextInputLayout>
<Button
android:id="#+id/barcode_activity_button_cancel"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/barcode_activity_manual_input_check_box"
android:text="Cancel" />
<Button
android:id="#+id/barcode_activity_button_ok"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_below="#+id/barcode_activity_manual_input_check_box"
android:layout_toEndOf="#+id/barcode_activity_button_cancel"
android:text="Ok" />
<TextView
android:id="#+id/barcode_activity_text_view_warning"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textContainer"
android:layout_toRightOf="#+id/barcode_activity_image_view_warning"
android:paddingTop="5dp"
android:text="Serial doesn't match Workorder"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#f00000"
android:textSize="13dp" />
<ImageView
android:id="#+id/barcode_activity_image_view_warning"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_below="#+id/textContainer"
android:background="#drawable/warning" />
<CheckBox
android:id="#+id/barcode_activity_manual_input_check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/barcode_activity_image_view_warning"
android:text="Allow Serial In Workorder"
android:textSize="13dp" />
</RelativeLayout>
and here is my main file >
inputFieldDialog = new Dialog(this); // CASTING
//inputFieldDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
inputFieldDialog.setContentView(R.layout.aligment_manager_manual_input_layout); // INFLATING VIEW
Button cancelInputButton, confirmInputButton; //declaring BOXES
final EditText inputField;
TextView warningTextView;
ImageView warningImageView;
CheckBox warningCheckBox;
cancelInputButton = (Button) inputFieldDialog.findViewById(R.id.barcode_activity_button_cancel); //casting
confirmInputButton = (Button) inputFieldDialog.findViewById(R.id.barcode_activity_button_ok); //casting
inputField = (EditText) inputFieldDialog.findViewById(R.id.barcode_activity_input_editText); //casting
warningTextView = (TextView) inputFieldDialog.findViewById(R.id.barcode_activity_text_view_warning); //casting
warningImageView = (ImageView) inputFieldDialog.findViewById(R.id.barcode_activity_image_view_warning); //casting
warningCheckBox = (CheckBox) inputFieldDialog.findViewById(R.id.barcode_activity_manual_input_check_box); //casting
warningTextView.setVisibility(TextView.INVISIBLE); //sets warnings invisible
warningImageView.setVisibility(ImageView.INVISIBLE); //sets warnings invisible
warningCheckBox.setVisibility(CheckBox.INVISIBLE); //sets warnings invisible
cancelInputButton.setOnClickListener(new View.OnClickListener() { //listeners for the buttons
#Override
public void onClick(View v) {
inputFieldDialog.hide();
}
});
confirmInputButton.setOnClickListener(new View.OnClickListener() { //listeners for the buttons
#Override
public void onClick(View v) {
scanResults = String.valueOf(inputField.getText());
scanBarcodeText.setText(inputField.getText());
editor.putString("boxID", String.valueOf(inputField.getText())); //saves the data as antenaNamein shared prefrences
editor.commit();
if (checkIfIdMatched(String.valueOf(inputField.getText())) == true) { //checkks if id is maching the one in the workorder
aligmentManagerClass.scanFromBarcodeApproved(); //ID MACHED
if (mainDialog != null) {
mainDialog.show();
}
loaderScreenMainText.setText("initlizing WiFi");//shows the user on screen message
wifiWrapper myWifiWrapper = new wifiWrapper(); //- INIZILIZING WIFI
myWifiWrapper.checkWifiState(getApplication(), callbackFunctionForisWifiOn);
} else {
loaderScreenMainText.setText("Scan Doesn't Match Data In Workoder"); // notify onScreen User
if (mainDialog != null) { // hides the loading dialog
mainDialog.hide();
}
AlertDialog wrongNumberDialog = getAlertDialogForWrongId(); //shows to user alert dialog for Wrong Number
wrongNumberDialog.show(); // show it
}
}
For remove white space...
Use "View.GONE" property of setVisibility() method rather than "TextView.INVISIBLE".
Set below code for hide views
warningTextView.setVisibility(View.GONE);
warningImageView.setVisibility(View.GONE);
warningCheckBox.setVisibility(View.GONE);
And for visible view just user
warningTextView.setVisibility(View.VISIBLE);
warningImageView.setVisibility(View.VISIBLE);
warningCheckBox.setVisibility(View.VISIBLE);
You can add buttons dynamically by creating buttons in Java file
Add this XML to dialog like dialog.addView(...)
Then Create Dynamically Buttons by according to values like
for(){
Create Buttons and add to above layout
layout.addView(button);
}
Hope it will help.
I am using an AlertDialog created using android.suport.v7.app.AlertDialog and I am having a custom layout for the Dialog with a few EditTexts and a few TextViews.
The TextViews that are used are initially having their visibility set to GONE.
I am using the TextViews mainly to prompt the user for incorrect inputs in the EditText fields.
So when I try to toggle the visibility of the TextView to VISIBLE for showing an error message, the visibility does not change.
My XML File for layoutS is:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/contactName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:hint="#string/sampark_naam"
android:layout_marginEnd="5dp"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:layout_marginRight="5dp">
<requestFocus />
</EditText>
<TextView
android:id="#+id/noName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/no_name_error"
android:textColor="#android:color/holo_red_dark"
android:layout_marginEnd="5dp"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:layout_marginRight="5dp"
android:visibility="gone"/>
</LinearLayout>
The AlertDialog used is:
final Context context = view.getContext();
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View aDrishya = layoutInflater.inflate(R.layout.layoutS, null, false);
vNaam = (EditText) aDrishya.findViewById(R.id.contactName);
nameError = (TextView) aDrishya.findViewById(R.id.noName);
sSanddok = new AlertDialog.Builder(context)
.setView(aDrishya)
.setTitle("Add A New Contact")
.setPositiveButton("Add +", new PositiveButton(context))
.setNegativeButton("Pick", new null);
sSanddok.show();
In the positive button I check for the contactName entered as:
if(vNaam.getText().toString().equals("")) {
Toast.makeText(this, "No Name", Toast.LENGTH_SHORT).show();
nameError.setVisibility(View.VISIBLE);
} else {
nameError.setVisibility(View.GONE);
}
It is showing the Toast but it's not showing the TextView.
Any idea what's wrong here and how to fix it?
Hi can you try to change and run this code, See if it works..
Alert dialog changes :
sSanddok = new AlertDialog.Builder(context)
.setView(R.layout.layoutS)
.setTitle("Add A New Contact")
.setPositiveButton("Add +", null)
.setNegativeButton("Pick",null);
sSanddok.show();
sSanddok.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//if edit text value is empty do this
TextView tv = (TextView)sSanddok.findViewById(R.id.noName);
tv.setVisibility(View.VISIBLE);
}
});
TextView visibility in xml is set to gone..
Hi this is working for me...Try this code pls
I have the following text with me.
"I drink tea and coffee". Now the requirement is to change this text to "I drink EditText AND EditText"....Here the EditText is a edit box where in the user can enter answers once it is clicked. I need to make this change pro grammatically.
Any suggestions on this, as to how this can be achieved????
You could use the following code in button's click event handler:
String str = "I drink tea and coffee";
String editTextString = editText.getText().ToString();
str.replace("coffee", editTextString);
str.replace("tea", editTextString);
You can ctreate activity structure in your layout xml file:
<LinearLayout 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:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I drink " />
<Button
android:id="#+id/firstAnswer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="EditText" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" and " />
<Button
android:id="#+id/secondAnswer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="EditText" />
</LinearLayout>
And set listners to your buttons
private String[] answers = { "tea", "coffee", "juice", "compote" };
...
Button firstAnswer = (Button) findViewById(R.id.firstAnswer);
firstAnswer.setOnClickListener(new OnClickListener() {
private int position = 0;
#Override
public void onClick(View view) {
((Button) view).setText(answers[position]);
position++;
if (position == answers.length)
position = 0;
}
});
By using getText()
Example
Button mButton;
EditText mEdit;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mButton = (Button)findViewById(R.id.button);
mEdit = (EditText)findViewById(R.id.edittext);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
Log.v("EditText", mEdit.getText().toString());
}
});
}
after that
mEdit.setText("Tea");
EditText et=(EditText)findViewByID(R.id.yourId);
Button bt=(Button)findViewById(R.id.yourBtId);
bt.setOnClickListener(
new View.setOnClickListener()
{
public void onClick(View v)
{
et.setText("You Drink EditText");
}
});
Put These code in onCreate() method
Use ViewSwitcher. This widget displays one of two views it contains:
<ViewSwitcher
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</ViewSwitcher>
And then, when button is pressed, switch it and load text from EditText to TextView or vice versa:
editText.setText(textView.getText());
viewswitcher.showNext();
or
textView.setText(editText.getText());
viewswitcher.showPrevious();
Refer to this for details.
You can use 4 textboxes with texts "I drink" ,"tea" , " and ", "coffee" respectively.
On the ontouch event of the 2nd and 4th textbox, you can display a textbox or edittext and edit the text. On a button click you can get the texts from the textboxes and display it again.
Just Use this : yourTextField.setText("..."+yourEditText.getText().toString());