Setting Content in a EditText - java

I am developing a android calculter and I want to add the number the user clicks when he clicks its button
i added the onclick like this
android:onClick="number(1)"
the number inside the brackets is the number that i want it to be appended inside the EditText
and the code of the main activity and the function is
public void number(int medo){
EditText result = (EditText) findViewById(R.id.result);
result.setText(result.getText() + " " + medo);
}
but when i click any button while testing the app it crashes so may anybody tell me how to fix this but fast please

Your method needs to have a View parameter, which will contain the button you clicked.
So, your code could look like this:
public void number(View v) {
EditText result = (EditText) findViewById(R.id.result);
// get the text from the button that was clicked and add it to the EditText
result.setText(result.getText() + " " + ((Button)v).getText().toString());
}
You can't set the argument in XML. It should look like this:
android:onClick="number"

Also i think you have to call toString.
result.getText().toString()

the onCLick should be a method that has a view parameter in it.
this View represents the View (in this case Button) was clicked.
you method should be like that:
public void number(View view)
to solve your problem i will suggest putting android:tag in the xml.
for the Button you showed you will do:
android:tag="1"
android:onClick="number"
and in the number function you will do something like that:
public void number(View view)
{
result.setText(result.getText() + " " + view.getTag().toString);
}
in addition, i will highly suggest to make result to a global variable and initialize it in the onCreate() instead, it will make the code better and efficient

Related

How can I add a textview to a linear layout with an onclick button listener?

What I need is for the textview to be added onto a linear layout where it will look organised and nice. Whenever the button is clicked again, it should replace the old textview and update it again.
At the moment, the button onclick listener will produce a textview, but I don't like it because it looks messy and unorganised.
I tried doing this:
varlinear.addView(varkebabTotal);
but it caused an error.
I have looked at other examples but they didn't explain how it will work with an onlick listener.
Here's the code for what happens when the button is clicked:
varKebab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = "Kebab Wrap";
if (menu.containsKey(name)) {
kebabquantity = list.get(name);
if (kebabquantity == null) {
kebabquantity = 0;
}
kebabquantity++;
list.put(name, kebabquantity);
//kebab qty calc
double kebabTotal = kebabquantity * menu.get(name);
overallTotal = overallTotal + menu.get(name);
varkebabTotal.setText(String.format("%s %s # £%s = £%.2f", kebabquantity.toString(), name, menu.get(name), kebabTotal));
varTotalPrice.setText(String.format("Total = £%.2f", overallTotal));
varlinear.addView(varkebabTotal); // this line caused an error
}
}
});
Edit:
The error I received is when I tested the app, and when I click the button, the app stops. It shuts itself down due to that one line: varlinear.addView(varkebabTotal);
The variables are as follows:
varkebabTotal = (TextView) findViewById(R.id.kebabTotal);
varTotal = (TextView) findViewById(R.id.TotalPrice);
varlinear = (LinearLayout) findViewById(R.id.myLinear);
one method you can try is to set varkebabTotal.setVisibility(View.GONE); when you initialize the TextView, and then on your onClick event, you can change it to varkebabTotal.setVisibility(View.VISIBLE);

Set multiple listeners to one method

I am learning to develop on android on android studio and I encountered a problem.
I have multiple EditText controls for user info: First Name, Last Name, Address and I want them to behave the same when they are in focus and out of focus.
For example, my emailInput EditText control has "Email Address" as its text property. When the user clicks "Email Address" disappears and if the user didn't add any input and leaves the control "Email Address". This is what this method does:
private string emailAddress = "Email Address";
public void onFocusChange(View view, boolean focus)
{
(EditText) email = (EditText) findViewById(R.id.emailInput);
if(!focus && (email.getText()).equals(""))
{
email.setText(emailAddress);
}
else if(focus && (email.getText()).equals(emailAddress))
{
email.setText("");
}
}
I have like 20 controls and I don't want to copy and paste the same code and change the variables.
I have two questions: Can I get the id of the control that calls the onFocusChange method so the first line becomes ->
(EditText) ctrl = (EditText) findViewById(R.id.(this.getId());
and can I add a new property "Initial Text" to EditText controls so I can get something like this ->
if(!focus && (ctrl.getText()).equals(""))
{
ctrl.setText(ctrl.getInitialText());
}
else if(focus && (ctrl.getText()).equals(ctrl.getInitialText()))
{
ctrl.setText("");
}
EDIT: This is sort of like creating my own control that inherits from the EditText class. I'm just adding an object variable(Initial Text) and a method(getInitialText). Can I create my own control like this and still have the Drag and Drop feature in android studio?
Thanks! :D
The behaviour you describe is exactly what the android:hint attribute on any EditText does.
http://developer.android.com/reference/android/widget/TextView.html#attr_android:hint

Setting a TextView to visible from invisible based on an if statement

I have several strings of text on a screen that are set to invisible when the application starts. When a button is clicked on another screen, I want a specific string to become visible. Ultimately I want to have a few strings, of the several, become visible as a result of clicking this button.
public void buttona0Click(View view){
setContentView(R.layout.report_screen);
buttonClicked2 = 1;
if(buttonClicked1==1){
setVisibility(R.id.textView2.VISIBLE);
}
}
I am primarily looking for guidance on this line
setVisibility(R.id.textView2.VISIBLE);
I am new to programming in general, so I don't know if what I've said makes sense to most of you. Is .setText an alternative?
Write your own algo:
Use one boolean
view VISIBLE and GONE based own above boolean variable
You need to instantiate your TextView first. So the easiest way to begin is to declare them before onCreate() and outside of any other method so they are member variables
public class MyActivity extends Activity
{
TextView tv1, tv2, etc...;
public void onCreate(...)
{
super.onCreate(...);
setContentView(R.layout.my_layout);
tv1 = (TextView) findViewById(R.id.textView1);
...
}
Then in your onClick() change the Visibility which takes an int value
public void buttona0Click(View view){
buttonClicked2 = 1;
if(buttonClicked1==1){
tv1.setVisibility(View.VISIBLE);
}
}
Note: please don't include the "..." above in your code. That is just omitted code that I assume you know how to handle already. Also, I took out setContentView() from the onClick() method because typically this should only be done once in onCreate().
I'm not sure about the logic inside there because I don't know what the buttonClicked1 variables are for but that is how to do the Visibility.
setVisibility() Docs
Is .setText an alternative?
This will simply set the text so if you have it already set in your xml then you don't need to...you can just change the Visibility as you are trying to do. If you haven't set it then you will need to with something like
tv1.setText("Hello World"); // input your own String or String resource
Make sure you call setVisibility(View.GONE) for all your TextViews in onCreate() after setContentView(). Then in your if clause set the visibility of selected textview to View.VISIBLE - textview.setVisibility(View.VISIBLE)
First findViewById of the TextView and in onClick function of your button set visibility of that textView as VISIBLE
TextView textView = (TextView) findViewById(R.id.textView1);
public void buttona0Click(View view){
buttonClicked2 = 1;
if(buttonClicked1==1){
textView.setVisibility(view.VISIBLE);
}
}

Problems with error: android.widget.LinearLayout cannot be cast to android.widget.EditText

I'm creating an EditText in onOptionsItemSelected() and trying to get it's information in onClick(). Here's the offending code:
onOptionItemSelected(MenuItem item){
...
EditText mealCalories = new EditText(context);
mealCalories.setId(MealCalId) //in this example it's just an integer 1.
...
}
onclick(View v){
EditText mealCaloriesInBox = (EditText)findViewById(mealCalId);
}
When I haven't selected an item from the menu (and thus haven't called onOptionItemSelected();) it doesn't crash when I click the button. However, when I actually have created the EditText and I click the button it crashes as it's trying to create the instance, giving me the aforementioned error. Any ideas on why it could be doing that?
EDIT
Here's more of my code:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Context context = getApplicationContext();
switch(item.getItemId()) {
case R.id.addMeal:
trackMealItems++;
mealCalId++;
mealFatId++;
mealCarbId++;
mealProteinId++;
//the base layout
LinearLayout root = (LinearLayout)findViewById(R.id.linearLayout1);
//make the layout that holds the meal item and add it to the base layout
LinearLayout mealItem = new LinearLayout(context);
mealItem.setId(trackMealItems);
mealItem.setOrientation(LinearLayout.VERTICAL);
mealItem.setLayoutParams(mealItemParams);
root.addView(mealItem);
//make the TextView that holds the name of the meal and add it to the mealItem layout
EditText mealName = new EditText(context);
mealName.setLayoutParams(mealNameParams);
mealItem.addView(mealName);
//make the TextViews that hold the information about the meal and stick them in a
//horizontal LinearLayout
LinearLayout mealStats = new LinearLayout(context);
mealStats.setOrientation(LinearLayout.HORIZONTAL);
mealStats.setLayoutParams(mealStatParams);
mealItem.addView(mealStats);
EditText mealCalories = new EditText(context);
mealCalories.setId(mealCalId);
mealCalories.setLayoutParams(mealStatParams);
mealStats.addView(mealCalories);
EditText mealFat = new EditText(context);
mealFat.setId(mealFatId);
mealFat.setLayoutParams(mealStatParams);
mealStats.addView(mealFat);
EditText mealCarbs = new EditText(context);
mealCarbs.setId(mealCarbId);
mealCarbs.setLayoutParams(mealStatParams);
mealStats.addView(mealCarbs);
EditText mealProtein = new EditText(context);
mealProtein.setId(mealProteinId);
mealProtein.setLayoutParams(mealStatParams);
mealStats.addView(mealProtein);
return true;
case R.id.removeMeal:
LinearLayout removeMe = (LinearLayout)findViewById(trackMealItems);
removeMe.setVisibility(View.GONE);
trackMealItems--;
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v){
EditText mealCaloriesInTextBox = (EditText)findViewById(mealCalId);
}
You seem to be using two different values: MealCalId when you create your EditText and mealCalId when you call findViewById. That's one possible problem. The other is that if you have more than one view with the same id, findViewById will not necessarily return the one you want.
EDIT
At first glance, your code looks like it should work. I don't know what's going wrong, but I have a suggestion for a work-around. When you create the view, instead of assigning it an ID, assign it a tag:
mealCalories.setTag(mealCalId);
(The int value will be autoboxed to an Integer.) Then in your onClick handler, retrieve it by tag:
EditText mealCaloriesInTextBox =
(EditText) getContentView().findViewWithTag(mealCalId);
If there's any kind of funny interaction with view IDs, this technique will avoid them.
If that doesn't work (or if you prefer anyway) you can also try diagnosing the ID-based retrieval using the Hierarchy Viewer.
For those who are having this error for the same reason I did....
Just try cleaning your project and re-building.
Solved it for me.
i tried to run your code and what i found is that
when menu item is not clicked and button is clicked, the edit text is null.
So if you will call any method on this object, it will crash with NULLPointerException
When menu item is clicked and then button is clicked, the edit text is not null so you call any method on this object.

How do I change TextView Value inside Java Code?

I am working on a android program. A user clicks on a button I do some math and I would like to change the values that I have on my view in some TextView objects. Can someone please tell me how to do it in my code?
I presume that this question is a continuation of this one.
What are you trying to do? Do you really want to dynamically change the text in your TextView objects when the user clicks a button? You can certainly do that, if you have a reason, but, if the text is static, it is usually set in the main.xml file, like this:
<TextView
android:id="#+id/rate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/rate"
/>
The string "#string/rate" refers to an entry in your strings.xml file that looks like this:
<string name="rate">Rate</string>
If you really want to change this text later, you can do so by using Nikolay's example - you'd get a reference to the TextView by utilizing the id defined for it within main.xml, like this:
final TextView textViewToChange = (TextView) findViewById(R.id.rate);
textViewToChange.setText(
"The new text that I'd like to display now that the user has pushed a button.");
First we need to find a Button:
Button mButton = (Button) findViewById(R.id.my_button);
After that, you must implement View.OnClickListener and there you should find the TextView and execute the method setText:
mButton.setOnClickListener(new View.OnClickListener {
public void onClick(View v) {
final TextView mTextView = (TextView) findViewById(R.id.my_text_view);
mTextView.setText("Some Text");
}
});
First, add a textView in the XML file
<TextView
android:id="#+id/rate_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/what_U_want_to_display_in_first_time"
/>
then add a button in xml file with id btn_change_textView and write this two line of code in onCreate() method of activity
Button btn= (Button) findViewById(R.id. btn_change_textView);
TextView textView=(TextView)findViewById(R.id.rate_id);
then use clickListener() on button object like this
btn.setOnClickListener(new View.OnClickListener {
public void onClick(View v) {
textView.setText("write here what u want to display after button click in string");
}
});

Categories

Resources