Dynamically change the name of the resource file to be used? - android

It is possible to do something like:
if (colorScheme == 1)
button.setBackgroundResource(R.drawable.button + "_1")
in order to use R.drawable.button_1 as the resource for this button in color scheme 1, if there are files named button_1.png, button_2.png, button_3.png in drawable folder.
(dynamically use different resource file for the same UI element based on the color scheme being used?)
Thanks,

I've done something simular using getIdentifier():
int resId = context.getResources().getIdentifier("button_1","drawable",context.getPackageName());
button.setBackgroundResource(resId);

In order for it to be dynamic, there will be some code required. You can set up your layout in xml Like this:
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
And then reference it in your code like this:
int resId = context.getResources().getIdentifier("button_1","drawable",context.getPackageName());
Button button = (Button view.findViewById(R.id.button1);
button.setBackgroundResource(resId);
I haven't tested this, but this should give you the idea.

Put R.drawable.button_n in an array int res[] and then call them by button.setBackgroundResource(res[i])

Related

How we define the id in kotlin without any use of third party library?

In java, we used to define the id by using findviewbyid. I am Wondering how we can define the id in kotlin without any use of third party library.
You don't have to define the view id's in Kotlin. All you have to do is use a non declared variable which has same name as the view in layout xml file. This reduces the chance of you running into a bug.
Assume you have this TextView in the layout xml
<TextView
android:id="#+id/mytextview"
android:layout_width="match_parent"
android:layout_height="50dp"
android:textSize="18sp"/>
then this is how you can access this by a variable name mytextview, without declaring it in the file. This is how you would set the text
mytextview.text = "My text view"
You can read more at https://kotlinlang.org/docs/tutorials/android-plugin.html
Another way could be following but I wouldn't suggest it
private var textview: TextView? = null
textview = findViewById(R.id.mytextview) as TextView // old way
textview = findViewById<TextView>(R.id.mytextview) // new way

set textsize for multiple textview with same ID

Is it possible to set textsize for multiple textview with same ID ? I have them with android:id :"#+id/lbl" ? Actually I set dp based on folder values/dimen.xml
TextView lbl=(TextView) findViewById(R.id.lbl);
lbl.setTextSize(dp);
The first textview only get this effect, but the rest of textview dont get this effect. Let me know how to solve this problem.
You need to do it separately as every activty/fragment/adapter has its own layouts (xml). In R.java they would have its own unique number.
android:textSize="24sp"
Everytime you add the views in XML, just add the text size
In android platform each view must have a unique id identified by "android:id" attribute of view. Although you are able to define multiple views with same id but android very first declaration and leaves the rest view as having no id.
Lets have an example now:
<TextView
android:id="#+id/response_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="27dp"
android:layout_toLeftOf="#+id/scan_format"
android:text="TextView" />
<TextView
android:id="#+id/response_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/response_text"
android:layout_marginBottom="74dp"
android:layout_toLeftOf="#+id/response_text"
android:text="Trepeattet" />
here are two textviews with same id, and now see R.java
public static final int radio=0x7f05002f;
public static final int response_text=0x7f050040;
public static final int scan_button=0x7f05003c;
public static final int scan_content=0x7f05003e;
public static final int scan_format=0x7f05003d;
in R.java only one textview is declared with its id(this hex id is created by platform compiler itself when you first run your code).
So although application does not produce any error in compile time or run time but will not do anything to any other view with same id either except very first one because of only one reference available that belongs to first textview.
As per this post here is what you can do:
View IDs are plain integers, so you can simply have an array of ids you want to change. For example:
int[] ids = { R.id.lbl1, R.id.lbl2, ... };
for (int id: ids) {
TextView lbl=(TextView) findViewById(id);
lbl.setTextSize(dp);
}
This will work.
You can get all TextViews of your parent view. Then check their ids in a loop

Android button id

If I have created a button in xml and i want to use this button multiple times but give them unique id's, how do i do that? I don't know how many buttons i will have, so i can't create a number of buttons in my xml-file. I want to be able to change the buttons id while running the program. I've tried to do button.setId() but then everything breaks and wont work.
You can make an independent button.xml file (or even do it as a style), then inflate that in your code as needed.
For instance, let's say you have an array of strings representing a list of countries, and you want a button for each country. This is nice because if you add or remove any, you only have to modify the array, not your xml or the for loop.
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
String[] countries = {"US", "Canada", "UK", "Australia"};
String country;
// Don't forget to add the following layout to your xml.
LinearLayout buttonLayout = (LinearLayout) findViewById(R.id.buttonLayout);
buttonLayout.removeAllViews();
for (int i = 0; i < countries.length(); i++) {
country = countries.getString(i);
Button temp = (Button)inflater.inflate(R.layout.button);
// Don't forget that id is an int, not a string.
button.setId(id);
button.setText(country);
buttonLayout.addView(temp);
}
Bonus: you can also include this button in another xml file, and update the id in the include statement as follows:
<include layout="#layout/button"
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 1"
/>
The question is not very clear, but I think you can use dynamic button creation.
Button button = new Button();
// init it here
layout.add(button, new LayoutParams(...));
give id in xml like
<Button android:id="#+id/close"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="#string/title_close" />
When you are not sure of the instances you need in your application of a certain widget, then go for dynamic creation.
XML is mostly for static creation.

Dynamic Resource Loading Android

I'm trying to find a way to open resources whose name is determined at runtime only.
More specifically, I want to have a XML that references a bunch of other XML files in the application apk. For the purpose of explaining, let's say the main XML is main.xml and the other XML are file1.xml, file2.xml and fileX.xml. What I want is to read main.xml, extract the name of the XML I want (fileX.xml), for example, and then read fileX.xml. The problem I face is that what I extract form main.xml is a string and I can't find a way to change that to R.raw.nameOfTheFile.
Anybody has an idea?
I don't want to:
regroup everything in one huge XML file
hardcode main.xml in a huge switch case that links a number/string to the resource ID
I haven't used it with raw files or xml layout files, but for drawables I use this:
getResources().getIdentifier("fileX", "drawable","com.yourapppackage.www");
to get the identifier (R.id) of the resource. You would need to replace drawable with something else, maybe raw or layout (untested).
I wrote this handy little helper method to encapsulate this:
public static String getResourceString(String name, Context context) {
int nameResourceID = context.getResources().getIdentifier(name, "string", context.getApplicationInfo().packageName);
if (nameResourceID == 0) {
throw new IllegalArgumentException("No resource string found with name " + name);
} else {
return context.getString(nameResourceID);
}
}
There is another method:
int drawableId = R.drawable.class.getField("file1").getInt(null);
According to this blog it's 5x times faster than using getIdentifier.

Android: Get an attribute's value from an XML item

Is there an easy way to grab a attribute value from an xml item in your Java class definition? I'm looking for something like this:
// In xml layout:
<TextView android:id="#+id/MyXMLitem" android:textColor="#000000" />
// in Java Class definition
String some_text_color;
some_text_color = R.id.MyXMLitem.attr.textColor; // I'd like this to return "#000000"
I know you can grab similar xml attributes from the converted objects using getters/setters like View.getText()... I'm just wondering if there's a way to grab an xml attribute right from the item itself.
Views take the XML values and store them into class level variables in their constructors so it's not possible to get values from the object itself once the layout has been created.
You can see this in the source of the View object at https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/view/View.java
if you search for AttributeSet (which is the object used to pass the XML layout values to the constructor).
You can use XmlResourceParser to read data straight from XML resources.
<TextView android:id="#+id/MyXMLitem" android:textColor="#000000" />
You can use getCurrentTextColor().
TextView tv = (TextView)findViewbyId(R.id.MyXMLitem);
String color = Integer.toHexString(tv.getCurrentTextColor());
It returns ff000000 instead of #000000 though.

Categories

Resources