Ok my pattience is gone now...I tried for 30 minutes to make this simple thing work but I failed so bad.Maybe it is because I started directly with android,no java...I studied c++ before,and in c++ this was so easy to do...
I have a button in a xml file:
<Button android:text="Button"
android:layout_width="wrap_content"
android:id="#+id/button1"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="108dp">
</Button>
And in my java file I have a string like this:
String test = new String();
test = "google";
I 've already set up the onclick listener for the button so there is no problem.
My question is if:
Button buttonx = (Button)findViewById(R.id.button1);
How can I compare if onClick(onclick code is already made) buttonx's text = the string test that is "google".
I tried with getText,setText...but nothing...
OK. First things first: Strings are completely different in Java to C++. In fact, Objects are pretty different all-round.
String test = new String();
test = "google";
does not do what you think it does.
What this does is create a new empty String object and store a reference to it in test. The next line stores a reference to a constant String "google" in test and makes the empty String you constructed in the previous line eligible for garbage collection. This is completely different to C++, where the second line would actually call the = operator on the String class. You can kinda think of everything in Java being a pointer (but not really), so assignment in Java behaves like pointer assignment in C++ (but not really).
Back to your question.
Something like this might work:
String test = "google";
Button b = ...;
if (test.equals(b.getText()) {
// whatever
}
Remember that although Java and C++ share some syntax similarities they are really completely different languages. Java references kinda behave like pointers, but not really.
Really.
String test = new String();
test = "google";
Button buttonx = (Button)findViewById(R.id.button1);
if (test.equals(buttonx.getText())) {
// it's equal
}
if (button.getText().toString().equalsIgnoreCase(test))
Toast.makeText(this, "Button text equals!", Toast.LENGTH_SHORT).show();
else
Toast.makeText(this, "Button text is not the same.", Toast.LENGTH_SHORT).show();
Related
In the app I'm building, I'm hoping to have several different guides / tutorials that will each contain several paragraphs and hopefully pictures in them. Right now the only thing I would know to do is to have all of the different texts written out long form in my strings resource file. I would then need to have separate layouts and fragments for each tutorial.
Is there an easier way? Can I separate my strings resource file at least so that I don't have that one file completely bogged down? Could I maybe import the text from a separate file?
Yes, you can. you need to set text programmatically. You need only one layout for all of these same type information page.
Let's say you have
<TextView
android:id="#+id/text_view_id"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/hello" />
You can get that text view from java activity like below and set the text you want..
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView helloTextView = (TextView) findViewById(R.id.text_view_id);
helloTextView.setText(R.string.user_greeting);
}
}
you can do this setText process by adding a switch, if or any conditional checking process like below
switch(expression) {
case value :
helloTextView.setText(R.string.firstPageText);
break;
case value :
helloTextView.setText(R.string.secondPageText);
break; // optional
// You can have any number of case statements.
helloTextView.setText(R.string.defaultText);
// Statements
}
PS: I think you can use different text style while you creating resource text. You can follow this https://www.myandroidsolutions.com/2017/09/29/android-html-textview/#.W9pu1mgzaUk for it.
EditText text1;
text1 = (EditText) findViewById(R.id.editText1);
text1.getText().toString();
Hi im new to android programming an need a little help. :) I just want to clarify if text1 is an object? Because it can call a method. But if text1 is an object how come that there is no "new" keyword. Thanks in advance for any response. :)
It is not necessary that all variables do initialization with new keyword.
Like if you write
String s = "";
Your String has been initialized without new keyword.
Same like this EditText is provided initialization in findViewById(). Here findViewById returned Edittext instance.
I suggest you complete Java Tutorial before continue work on Android. Because Android is based on Java language.
EditText is derived from the Super class View. Here findViewById method is returning an an object of the View class. You are explicitly typecasting it to EditText and assigning it to text1. So new is not required. It is being managed in findViewById method. Alternatively you can do this as:
EditText text1;
text1 = new EditText(An instance of Context); //Create an object of Edittext class
Now do whatever with this object text1.
It's me 2 years after, Now I want to answer your question bud. I know you just started and had a dream of creating apps that will be used by others, and guess what? You already achieved that and you can now also create apps not just for android but for IOS since you're using flutter now, you also have your own account on google play store now. Listen Bud, on the first line you declare what type is the text1. on the second line that's where you declare the text1 as an object now, then on the third line you are then using that object's capabilities like getting text. You've learned so much in this journey, and still learning not just in programming but in life.
Should View objects (TextViews, EditTexts, etc) have a variable assigned to them in onCreateView even if the variable will never be used? Is it acceptable to just assign the object's id to the Fragment using findViewById and access the object by using its id instead?
More detail:
I have several EditText values that are being initialized like this:
EditText role1 = (EditText) root.findViewById(R.id.role1_edit_text);
EditText role2 = (EditText) root.findViewById(R.id.role2_edit_text);
// Six other similar entries truncated
However, I'm not using the actual variables for role1 so Android Studio suggests removing the variable and writing it like this:
root.findViewById(R.id.role1_edit_text);
root.findViewById(R.id.role2_edit_text);
// Six other similar entries truncated
I have never seen Views assigned this way and just happened upon it because I'm referencing the EditText by their ids in my methods like this:
// Accessing View objects using view ids
editTextIds = new int[]{R.id.add_location_role1_edit_text, R.id.add_location_role2_edit_text,
R.id.add_location_role3_edit_text, R.id.add_location_role4_edit_text,
R.id.add_location_role5_edit_text, R.id.add_location_role6_edit_text,
R.id.add_location_role7_edit_text, R.id.add_location_title_edit_text};
private boolean allFieldsHaveInput() {
for (int id : editTextIds) {
EditText editText = (EditText) getView().findViewById(id);
if (isTextEmpty(editText)) {
return false;
}
}
return true;
}
I have several such methods that use loops to go through all the EditText ids so switching to variables would definitely make the code more verbose. I feel like EditText editText = (EditText) getView().findViewById(id); might be slightly more expensive computationally, but with roughly eight Views it seems like a small price to pay so I don't have to write the method like this:
// Accessing View objects using a variable
private EditText role1, role2, role3, role4, role5, role6, role7, role8;
private boolean allFieldsHaveInput() {
return !isTextEmpty(role1) && !isTextEmpty(role2) && !isTextEmpty(role3)
!isTextEmpty(role4) && !isTextEmpty(role5) &&
!isTextEmpty(role6) && !isTextEmpty(role7) &&
!isTextEmpty(role8);
}
I have never seen View objects assigned without a variable in open source code so I'm a little concerned if removing the variable is a bad idea (especially since I'm planning to put the code up on GitHub).
From a readability standpoint would it be better to just assign variables like role1 even if the code becomes slightly more verbose?
You have already captured some of the nuances in the approaches. Personally, I'd choose code readability over performance in most cases. In your case however, I strongly believe an array approach would fare much better.
private EditeText[] roleEditTexts = new EditText[8];
// assign
This would also avoid the costly calls to findViewById() (if you are calling that code snippet multiple times).
So I'm trying to make a calculator app (just to get a hang of android development), and I noticed with some testing that the parseInt conversion from "String tack1" is causing the app to crash. Can someone tell me why? I can't seem to figure it out and I've been searching the internet for quite a while now. (hehe I'm a noob so please go easy) In the code below, I've modified a couple lines to make it seem obvious what it's supposed to print however it still crashes. Here's the code:
equals.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
oC = 1; //operator checker is on 1 (for plus)
switch(oC){ //check for operator clicked
case 0: break;
case 1:
tack1 = "1"; //INSERTED THIS TO MAKE OUTPUT OBVIOUS
tack1 = tack1.trim(); tack2 = tack2.trim(); //INSERTED BEFORE TO DEAL WITH WHITESPACE
numOne = Integer.parseInt(tack1); //CRASHES HERE
answer.setText(numOne);
modeChecker = 0; oC = 0;break;
NOTES ON PROGRAM(some of comments repeated and other stuff as well):
The tack1 = "1"; is to make output obvious
The tack1.trim() is to deal with whitespace
Yes whatever is in tack is a number and an integer (not even a negative integer)
Yes numOne is an integer and is defined wayy above (not in code listed here)
Sorry the indents are all messed up(after case 1) because of the comments I added
This is a section of my onClick method, so closing brackets aren't included in here.
Can someone please help me?
THANKYOU :D
I'd be willing to bet it's actually crashing on the following line AFTER the call to parseInt.
You're calling setText(int) on your TextView. When you pass an int to this method, that int is a pointer to a string resource...you're probably expecting an auto-conversion to a string. Since you are passing it an int that is generated in your application, it's extremely unlikely that this int also points to a string resource in your res/values/strings.xml file. What you really want to do is change numOne to a string first, which you can do inline:
Change
answer.setText(numOne);
to
answer.setText(String.valueOf(numOne));
and you're good to go.
This should be simple, but driving my crazy.
I have the following in my layout, not problems.
<TextView
android:id="#+id/birdinfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#00009c"
android:text="The Robin is a popular bird"
/>
Then I have these arrays which are set up with the list of string resources I have
private Integer[] DetailIds = {
R.string.barnaclegoose,
R.string.barnowl,
R.string.bewicksswan,
R.string.blackbird,
R.string.blackcap_male};
So I simply want to do this!
TextView detail = (TextView)findViewById(R.id.birdinfo);
detail.setText(DetailIds[0]);
setContentView(R.layout.main);
But this causes a force close error.
The string resource looks like this ( without header and footer info of course
<string name="barnaclegoose">What a wonderful goose!</string>
Added to this problem is if I use the resource directly to the resource
detail.setText(R.string.barnaclegoose);
For example, I still get a null exception! I'm sure I've done this before, but maybe I'm missing the obvious???
Any ideas appreciated.
( Eclipse, Android 1.5, Emulator with 1.5 )
I realize this is very old, but it came up in a search... Anyways, you need to call setContentView() before findViewById() etc:
setContentView(R.layout.main);
TextView detail = (TextView)findViewById(R.id.birdinfo);
detail.setText(DetailIds[0]);
your problem is for this line setContentView(R.layout.main);
at first you must define this this line then setText your textView
Thanks for the answer. but if you mean R.string.barnaclegoose for example, this is an integer value for the ID pointing to the string itself in the resource.
Anyway, I finally got it working by just creating the view inline instead of using an resource view.
For example
TextView t= new TextView(ctx);
t.setId(2);
t.setTextColor(Color.BLACK);
t.setText(DetailIds[bird]);
mLinearLayout.addView(t,params);
mLinearLayout.setBackgroundColor(Color.WHITE);
setContentView(mLinearLayout);
And that works perfectly.