I have a CardView in AndroidStudio with different ID's for each card. To search the different ID's i have made this:
for (int f = 0; f < mainGrid.getChildCount(); f++) {
if (f == count) {
int index = f;
String id = "food"+index;
foodName = findViewById(R.id.id);
foodName.getText();
}
}
But at foodName = findViewById(R.id.id); says that "Cannot resolve symbol id"
There's any other way to do it?
No matter how many times you loop, if you do not have a view named id in your layout, you will get the error you are getting.
You cannot use a variable called id and then tag it onto R.id.id (which resolves as a numeric id value)
If you want to find a view when you know only its name, see this:
Find view by name
Related
In my app, I want a counter from 0 to 8 to decide the number of players in a game.
Below there are 8 possible fields to write a name inside, which are all set to invisible. If the players-counter is set to 3 players, there should be the first 3 fields visible. Depending on the actual number of the counter, the visibility of the fields changes (1player = first field, 5 players = first 5 fields).
When the +1 (player) button is clicked, a certain method is activated. I tried to run a for-loop everytime the button is clicked. In this for-loop from 0 to "whatever amount" (max. 8 players) the actual fields should be found with "findById" and set to visible.
I tried it with a string resource (.xml) and I can get the text of the resource but with my thought process, I have to update the string resource to every number of the field (if 3 players: "field_" + "1", "field_" + "2", "field_" + "3").
How can I get and (most importantly) set/update a string resource for this specific purpose?
(Switch is too inefficient and I can't use a string with the findViewBy Id()-method by updating the String (not string resource) like mentioned before.
Please help, and accept the fact that I'm new to Android Studio for one week!)
You can use "getIdentifier" which takes a String parameter. So you can set the type as "id" in the second parameter of this method. This method returns the id of the view you want, but beware, it will throw a "FATAL EXCEPTION" if the id of the View doesn't exist. With this id, you can use findViewById to fetch the TextView and change its visibility. The "getIdentifier" method can be called from the "getResources()" method.
Below you can see what it would be like to make visible a TextView that has the id "textView1":
int id = getResources().getIdentifier("textView1", "id", getPackageName());
TextView textView = findViewById(id);
textView.setVisibility(View.VISIBLE);
Below you can see how you would make 8 TextView with id 1 to 8 visible:
TextView textView;
for (int i = 1; i <= 8; i++) {
int id = getResources().getIdentifier("textView" + i, "id", getPackageName());
textView = findViewById(id);
textView.setVisibility(View.VISIBLE);
}
So, just put the limit at i <= x , with x being the limit of players who will play:
TextView textView;
for (int i = 1; i <= totalPlayers; i++) {
int id = getResources().getIdentifier("textView" + i, "id", getPackageName());
textView = findViewById(id);
textView.setVisibility(View.VISIBLE);
}
Do you just want to make some EditTexts visible and others not? Personally I'd keep it simple, do the lookups once (in onCreate or wherever) and store the references in a list. Then when you need to display n fields, you can just iterate over the list and set the first n to VISIBLE and the rest to INVISIBLE.
I feel like it's fine to just list all the EditText IDs (R.id.field_1 etc) and generate your list of actual Views from that, but if that repetition bothers you, there's a few things you could do. Like:
set a tag attribute on each field in the XML, and use findViewWithTag to look them up, generating the lookup strings programmatically, like "field_" + i
do a similar thing with the resource ID, like in #Moises's answer
lookup their containing layout, use getChildCount and [getChildAt] to iterate over the views in that layout, and use isInstance to collect all the EditTexts in order3
create and add the EditTexts in code - you probably don't want to do this, but you could!
I'm not really sure what you mean about the string resource or what you're trying to do - I'd honestly just make a list of R.id.field_1 etc, iterate over that to do findViewById on each and store those in a new list, and you're done. Also my Java's a bit rusty so sorry no example code!
I'm trying to make a bukkit plugin, but this is a java problem. I have an enhanced for loop that, for some reason, only recognizes the declared loop variable in one specific instance. Here is an excerpt of the code:
for(String categoryName : catString)
{
if(this.getConfig().getConfigurationSection("Shops." + ShopName + ".Categories." + categoryName).getKeys(false).contains("SubCategories"))//If it has subcategories
{
Set<String> subCategories = this.getConfig().getConfigurationSection("Shops." + ShopName + ".Categories." + categoryName + ".SubCategories").getKeys(false);
String[] subCatString = new String[subCategories.size()];
int subCatAmount = subCategories.size();
holder = subCatAmount;
pageAmount = 0;
while(holder > 0)
{
pageAmount++;
holder -= 45;
}
Inventory[] subCategoryInvs = new Inventory[pageAmount];
cellIndex = 0;
pageIndex = 0;
holder = categoryAmount;
placeHolder = null; //Placeholder Inventory, will be loaded into the HashMap later, set to null so that it is fresh for subcategories.
while(pageIndex < pageAmount)
{
The line with the if statement recognizes the variable "categoryName", but in the very next line of code, where the Set is defined, I get a red underline telling me that "categoryName" is not a variable. In addition, if I add a statement before the if statement that uses "categoryName" in any way whatsoever, I am told that it isn't a variable. What gives?
BTW, I am using Eclipse, if that is relevant. Also, no, this isn't the complete for loop.
EDIT: I was able to work around it by using the non-enhanced for loop, meaning that instead of using categoryName, I had to use catString[index], which is fine, I guess. I'm still wondering what was wrong with my original for loop, as I used the same variable name throughout.
New Android/Java coder. Trying to replicate in Android app a project I built in MS-Access.
I have a layout with similar named TextViews, like text10, text12, etc. In MS-Access I can dynamically build those names with collection referencing:
For X = 10 To 15
Me.Controls("text" & X) = Null
Next
There is no array required. So looking for structure in java that can accomplish the same functionality.
I want to dynamically set background color of multiple TextView based on two inputs. One is to build TextView reference and the other is a state indicator that will determine color.
Here is one procedure calling setSubColor:
public void Clear(MenuItem mi) {
puz.setText("");
sol.setText("");
for (int i=0; i<26; i++) {
setSubColor(aryA[i].charAt(0), 0);
What I have so far for setSubColor:
public void setSubColor (char c, int i) {
TextView v = (TextView) >>>dynamically reference v using name built with ("tv" + c)
if (i == 0) {v.setBackgroundColor(Color.TRANSPARENT);}
else {v.setBackgroundColor(Color.YELLOW);}
You can get the res id from the res name at runtime. So if your textview had name "text1", you could get the integer id by using:
int id = getResources().getIdentifier("text1", "string", getPackageName());
TextView view = findViewById(id);
But do so only as a last resort, it's error prone, slow and somewhat of an anti pattern.
EDIT by OP: No matter what the name argument is always returns 0 but marked as answer because it led to the following code that works exactly as I want, anti-pattern or not.
TextView v = (TextView) findViewById(getResources().getIdentifier("tv" + c, "id", getPackageName()));
Instead of the TextView Id field use its Tag field.
String tag = (String)textView.getTag() and textView.setTag(Object tag) with tag instanceof String
then you can find the TextView by Tag
I'm working on an Android App, and I had the following code:
int digit = 0;
imageButton = (ImageView)findViewById(R.id.btn1);
numberedImage = (ImageView)findViewById(R.id.Digit1);
imageButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
digit++;
numberedImage.setImageResource(R.drawable.number + ((digit) + 1));
}
});
and some images on a drawable folder called number1, number2, and so on...
This code was working perfectly, and then, suddenly, it's not working anymore.
I want the ImageView to change the images each click, and what made me completely confused, is the fact that this code was working completely fine (even though it might be wrong some way, I'm not a programmer), and all of the sudden, it's not anymore...
After that I also tried using arrays and loops, but I encountered the same error:
"number cannot be resolved or is not a field"
which wasn't a problem before.
You have some misunderstanding. But may be fortunately(or unfortunately) your code gave you some successful result for which your misunderstanding was more firmed.
ImageView.setImageResource takes a resource id as parameter. not a image name. so when you are adding a digit to the resource id it is setting the image of next id. as your images' names are sequential so the ids were also sequential that's why you got successful result. But it is not guranteed that you will always be getting that done.
I guess previously it was working because there was an image named number in your resource. But now it is removed.
Proposed solution
Resources res = getResources();
String mDrawableName = "number" + digit + 1; // be sure those exist
int resID = res.getIdentifier(mDrawableName , "drawable", getPackageName()); numberedImage.setImageResource(resId);
please kindly use
for(int i=0;i<imageCount;i++){
int imageResId = getResources().getIdentifier("image" + i, "id", YourActivity.this.getPackageName());
numberedImage.setImageResource(imageResId);
}
in order to access image by resource name.
I have the following setup. In my xml i have a bunch of image views. I am trying to show only one of them depending on the number set in preferences and the day of week. This must be really easy but i can't find out the correct way to pass variable into findViewByID. Here is code snippet:
String groupName = "R.id."+prefs.getString("groupListKey", "<unset>")+"_"+(Calendar.getInstance().get(Calendar.DAY_OF_WEEK));
ImageView image = (ImageView) findViewById(groupName);
findViewById() expects you to pass it an integer that represents a resource identifier. You are trying to pass it a string
Your best bet would be to have a conditional statement that evaluates your day of week and returns you the proper ID rather than doing it the way you are
int resourceId = 0;
switch (Calendar.getInstance().get(Calendar.DAY_OF_WEEK)) {
case Calendar.SUNDAY:
resourceId = R.id.sundayView;
break;
case Calendar.MONDAY:
resourceId = R.id.mondayView;
break;
...etc
}
ImageView image = (ImageView) findViewById(resourceId);
findViewById receives an int as an argument, which is one of the generated in the R.id class.
You can have an array with your ids:
int[] imagesIds = new int[] { R.id.image1, ... R.id.image7 };
And then determine the index based on your conditions:
int imageIndex = ...
ImageView image = (ImageView) findViewById(imagesIds[imageIndex]);