android nested custom control xml attributes - android

I'm building an android compound control and nesting it into another compound control. The nested control, ThirtySecondIncrement, is a simple incrementing control with a minus then text field then plus so you can raise or lower the increment. I've made this control more general for my app allowing for a simple counter or 30-second increments or 1-minute increments. Here is the xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer name="counter_simple">0</integer>
<integer name="counter_30sec">1</integer>
<integer name="counter_1min">2</integer>
<declare-styleable name="ThirtySecondIncrement">
<attr name="countertype" format="integer"/>
<attr name="maxcount" format="integer"/>
</declare-styleable>
<declare-styleable name="IntervalEdit">
<attr name="label" format="string"/>
<attr name="incrementlabel" format="string"/>
</declare-styleable>
</resources>
My outer control includes labels and the ThirtySecondIncrement control. I would like to make the outer control flexible enough that I could include the "countertype" style to the outer control.
Can I do this in xml or must I do it programmatically? And if I do it programmatically how can I guarantee that it is done before the control is first used. Here is the code to extract the xml attributes:
public class ThirtySecondIncrement extends LinearLayout {
final int COUNT_INTEGER = 0;
final int COUNT_30SEC = 1;
final int COUNT_1MIN = 2;
//other code
public ThirtySecondIncrement(Context context, AttributeSet attr) {
super(context, attr);
TypedArray array = context.obtainStyledAttributes(attr, R.styleable.ThirtySecondIncrement, 0, 0);
m_countertype = array.getInt(R.styleable.ThirtySecondIncrement_countertype, COUNT_30SEC);
m_max = array.getInt(R.styleable.ThirtySecondIncrement_maxcount, MAXCOUNT);
m_increment = (m_countertype == COUNT_1MIN) ? 2 : 1;
array.recycle();
Initialize(context);
}
In a similar function in my IntervalEdit I could get an attribute relating to the counter and use a public function in ThirtySecondIncrement to set the countertype but, as stated, I'm wondering if there's a way to do this in xml.
thanks, in advance

I waited a while but got no answer so I solved the problem by having a helper function in the nested control to enable to set the property at runtime.
public void SetCounterType(integer countertype) {
//after checking that countertype is a valid value
m_countertype = countertype;
}
then in the constructor for IntervalEdit:
public IntervalEdit(Context context, AttributeSet attrs) {
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.IntervalEdit, 0, 0);
//other attributes read here
m_counterstyle = array.getInt(R.styleable.IntervalEdit_counterstyle, R.integer.counter_simple);
(ThirtySecondIncrement)findViewById(R.id.tsi).SetCounterStyle(m_counterstyle);
The SetCounterStyle function in the first custom control only sets the variable and doesn't force a redraw enabling me to call it from within the including custom control's constructor.
Any, that's how I solved it.

Related

Getting IAttributeSet From View Inflation Process

I'm working on a project that relies on the user adding a custom attribute to their Android layout elements. Just like MvvmCross' app:MvxBind. There are no custom view classes as the idea is that the user can use the normal Android views.
The problem is that in order to get the value of this tag I need to get the IAttributeSet that is used during the view inflation process and I can't find a method of doing so that suits my needs.
I have a working example using LayoutInflater.IFactory however, this requires me to set my own LayoutInflater/factory which, if the user is using a library such as MvvmCross, causes problems as only one factory can be set at once.
I'm looking for a way that I can get the IAttributeSet object whenever a view is inflated to check for my attribute that doesn't interfere with the standard LayoutInflater or LayoutInflater's from other libraries. Or if there is any way to get my attribute after the view has been inflated.
Thanks in advance!
Edit
I want to be able to get the value of MyAttribute from a view without subclassing views or creating custom views. This is easily accomplished with LayoutInflater.IFactory but this method interferes with libraries such as MvvmCross.
<TextView
android:layout_width="wrap_content"
android:layout_width="wrap_content"
app:MyAttribute="My attribute value" />
I'm not sure if I understand what you mean. Please refer to the following:
you could create a custom view and define its attribute in attrs.xml and when it is created from an XML layout, all of the attributes in the XML tag are read from the resource bundle and passed into the view’s constructor as an IAttributeSet
for example,here is a custom view named IconView
public class IconView : View
{
}
define some attributes in attrs.xml(Resources/values/attrs.xml)
<declare-styleable name="IconView">
<attr name="bg_color" format="color" />
<attr name="src" format="integer" />
<attr name="showIconLabel" format="boolean" />
<attr name="iconLabelTextColor" format="color" />
<attr name="iconLabelText" format="string" />
</declare-styleable>
then we could process the attributes in the view constructor when it is created (here define an Initialize method):
public IconView(Context context) : base(context)
{
Initialize(context);
}
public IconView(Context context, IAttributeSet attrs) : base(context, attrs)
{
Initialize(context, attrs);
}
private void Initialize(Context context, IAttributeSet attrs = null)
{
if (attrs != null)
{
// Contains the values set for the styleable attributes you declared in your attrs.xml
var array = context.ObtainStyledAttributes(attrs, Resource.Styleable.IconView, 0, 0);
iconBackgroundColor = array.GetColor(Resource.Styleable.IconView_bg_color, Color.Gray);
iconLabelTextColor = array.GetColor(Resource.Styleable.IconView_iconLabelTextColor, Color.ParseColor("#D9000000"));
_labelText = array.GetString(Resource.Styleable.IconView_iconLabelText);
_showIconLabel = array.GetBoolean(Resource.Styleable.IconView_showIconLabel, false);
var iconResId = array.GetResourceId(Resource.Styleable.IconView_src, 0);
if (iconResId != 0) // If the user actually set a drawable
_icon = AppCompatDrawableManager.Get().GetDrawable(context, iconResId);
// If the users sets text for the icon without setting the showIconLabel attr to true
// set it to true for the user anyways
if (_labelText != null)
_showIconLabel = true;
// Very important to recycle the array after use
array.Recycle();
}
...
}
You can refer to it for more details make custom view
I finally managed to figure this out.
Non-MvvmCross Solution
I stumbled across an article called "Layout Inflater: Friend or Foe?". I think this is the link but at the time of posting this answer it isn't working.
The author did an amazing talk on LayoutInflater and how he changed the Android LayoutInflater process so that he could intercept it for his library Calligraphy. The resulting solution is called ViewPump and it's written in Kotlin.
I have written the ViewPump library in Xamarin for use with non-MvvmCross projects: https://github.com/lewisbennett/viewpump.
MvvmCross Solution
MvvmCross uses a solution based on InflationX' ViewPump to do its binding and we can access it by first creating the below classes:
public class BindingBuilder : MvxAndroidBindingBuilder
{
protected override IMvxAndroidViewBinderFactory CreateAndroidViewBinderFactory()
{
return new ViewBinderFactory();
}
}
public class ViewBinderFactory : IMvxAndroidViewBinderFactory
{
public IMvxAndroidViewBinder Create(object source)
{
return new ViewBinder(source);
}
}
public class ViewBinder : MvxAndroidViewBinder
{
public override void BindView(View view, Context context, IAttributeSet attrs)
{
base.BindView(view, context, attrs);
// Do your intercepting here.
}
public ViewBinder(object source)
: base(source)
{
}
}
Then in your MvxAndroidSetup or MvxAppCompatSetup class add the following:
protected override MvxBindingBuilder CreateBindingBuilder()
{
return new BindingBuilder();
}
Done! I hope this helps someone :)

Re-using android's built in xml attributes for a custom view [duplicate]

I wrote a custom view that extends RelativeLayout. My view has text, so I want to use the standard android:text without the need to specify a <declare-styleable> and without using a custom namespace xmlns:xxx every time I use my custom view.
this is the xml where I use my custom view:
<my.app.StatusBar
android:id="#+id/statusBar"
android:text="this is the title"/>
How can I get the attribute value? I think I can get the android:text attribute with
TypedArray a = context.obtainStyledAttributes(attrs, ???);
but what is ??? in this case (without a styleable in attr.xml)?
use this:
public YourView(Context context, AttributeSet attrs) {
super(context, attrs);
int[] set = {
android.R.attr.background, // idx 0
android.R.attr.text // idx 1
};
TypedArray a = context.obtainStyledAttributes(attrs, set);
Drawable d = a.getDrawable(0);
CharSequence t = a.getText(1);
Log.d(TAG, "attrs " + d + " " + t);
a.recycle();
}
i hope you got an idea
EDIT
Another way to do it (with specifying a declare-styleable but not having to declare a custom namespace) is as follows:
attrs.xml:
<declare-styleable name="MyCustomView">
<attr name="android:text" />
</declare-styleable>
MyCustomView.java:
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView);
CharSequence t = a.getText(R.styleable.MyCustomView_android_text);
a.recycle();
This seems to be the generic Android way of extracting standard attributes from custom views.
Within the Android API, they use an internal R.styleable class to extract the standard attributes and don't seem to offer other alternatives of using R.styleable to extract standard attributes.
Original Post
To ensure that you get all the attributes from the standard component, you should use the following:
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TextView);
CharSequence t = a.getText(R.styleable.TextView_text);
int color = a.getColor(R.styleable.TextView_textColor, context.getResources().getColor(android.R.color.darker_gray)); // or other default color
a.recycle();
If you want attributes from another standard component just create another TypedArray.
See http://developer.android.com/reference/android/R.styleable.html for details of available TypedArrays for standard components.

SeekBarPreference seekBarIncrement

I want to set seekBarIncrement in an xml (rather than programmatically). I have tried many variants of adding it to my xml, including in a style, as seekBarIncrement="100", asp:seekBarIncrement="100" etc. Nothing breaks/complains, but there is no increment either --- the seekbar values all differ only by 1, not 100, and if I put a log in code, it hasn't seen any increase there either.
How do I get seekBarIncrement to take effect? I'm using android.support.v7.preference.SeekBarPreference.
(I extended the class and do see its value, it just doesn't show anywhere or seem to affect anything)
For reference, the Support Library defines the following:
<declare-styleable name="SeekBarPreference">
<attr format="integer" name="min"/>
<attr name="android:max"/>
<attr name="android:layout"/>
<attr format="integer" name="seekBarIncrement"/>
<attr format="boolean" name="adjustable"/>
<attr format="boolean" name="showSeekBarValue"/>
</declare-styleable>
which one can see set in the SeekBarPreference class itself:
TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.SeekBarPreference, defStyleAttr, defStyleRes);
mMin = a.getInt(R.styleable.SeekBarPreference_min, 0);
setMax(a.getInt(R.styleable.SeekBarPreference_android_max, 100));
setSeekBarIncrement(a.getInt(R.styleable.SeekBarPreference_seekBarIncrement, 0));
mAdjustable = a.getBoolean(R.styleable.SeekBarPreference_adjustable, true);
mShowSeekBarValue = a.getBoolean(R.styleable.SeekBarPreference_showSeekBarValue, true);
I added some math to OnPreferenceChangeListener that uses the defined increment to round the value properly.
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String key = preference.getKey();
if (key.equals(getString(R.string.key_scanning_delay))) {
final SeekBarPreference sbp = (SeekBarPreference) preference;
final int increment = sbp.getSeekBarIncrement();
float value = (int) newValue;
final int rounded = Math.round(value / increment);
final int finalValue = rounded * increment;
if (finalValue == value) return true;
else sbp.setValue(finalValue);
return false;
}
return true;
}
I'm using androidx.preference.SeekBarPreference, but there is probably little to no differences between these two libraries.
So, first check that it's the right preference. Then do the math. If the new calculated value is the same as the value the method was called with, return true so the value will be persisted. Most likely the values will differ on the first go. In that case, call the preference's setValue method again to update the view (and the value label if used). This time no math is needed (obviously) so it will return true and the value will be persisted. Finally return false so the original uncorrected value will be discarded.
In the documentation, the only xml attribute mentioned is android:thumb so what you're trying to do doesn't seem possible.
https://developer.android.com/reference/android/widget/SeekBar
I'd suggest going with either a programmatic approach or you could implement your own ViewGroup which accepts a parameter like seekBarIncrement and then passes it to the SeekBarPreference.

android defined attributes and custom attributes side by side on a custom view

I have created a custom view as well as corresponding custom attributes. For example
<declare-styleable name="stripbar">
<attr name="flowDirection" format="string"/>
</declare-styleable>
and
public Stripbar(Context context, AttributeSet attrs)
{
super(context, attrs);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.stripbar);
CharSequence flowDirection = ta.getString(R.styleable.stripbar_flowDirection);
String text = attrs.getAttributeValue("android", "text");
}
and
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ns="http://schemas.android.com/apk/res/com.ns">
<com.ns.Stripbar
android:id="#+id/aaa"
ns:flowDirection="RightToLeft"
android:text=”yoo hoo”/>
I receive null value for attribute text. I’m also aware of this and do not know how to resolve the issue.
To clarify, I need to obtain my custom attribute value as well as android predefined attribute value side by side?
Any help?
The problem is that your R.styleable.stripbar is actually an array of integers that contains just your flowDirection attribute.
To fix that, you should be able to replace your context.obtainStyledAttributes(attrs, R.styleable.stripbar); with context.obtainStyledAttributes(attrs, new int[]{R.attr.flowDirection, android.R.attr.text});
Then, you should be able to replace ta.getString( R.styleable.stripbar_flowDirection ) with ta.getString(0) and get the text with ta.getString(1).

Defining custom attrs

I need to implement my own attributes like in com.android.R.attr
Found nothing in official documentation so I need information about how to define these attrs and how to use them from my code.
Currently the best documentation is the source. You can take a look at it here (attrs.xml).
You can define attributes in the top <resources> element or inside of a <declare-styleable> element. If I'm going to use an attr in more than one place I put it in the root element. Note, all attributes share the same global namespace. That means that even if you create a new attribute inside of a <declare-styleable> element it can be used outside of it and you cannot create another attribute with the same name of a different type.
An <attr> element has two xml attributes name and format. name lets you call it something and this is how you end up referring to it in code, e.g., R.attr.my_attribute. The format attribute can have different values depending on the 'type' of attribute you want.
reference - if it references another resource id (e.g, "#color/my_color", "#layout/my_layout")
color
boolean
dimension
float
integer
string
fraction
enum - normally implicitly defined
flag - normally implicitly defined
You can set the format to multiple types by using |, e.g., format="reference|color".
enum attributes can be defined as follows:
<attr name="my_enum_attr">
<enum name="value1" value="1" />
<enum name="value2" value="2" />
</attr>
flag attributes are similar except the values need to be defined so they can be bit ored together:
<attr name="my_flag_attr">
<flag name="fuzzy" value="0x01" />
<flag name="cold" value="0x02" />
</attr>
In addition to attributes there is the <declare-styleable> element. This allows you to define attributes a custom view can use. You do this by specifying an <attr> element, if it was previously defined you do not specify the format. If you wish to reuse an android attr, for example, android:gravity, then you can do that in the name, as follows.
An example of a custom view <declare-styleable>:
<declare-styleable name="MyCustomView">
<attr name="my_custom_attribute" />
<attr name="android:gravity" />
</declare-styleable>
When defining your custom attributes in XML on your custom view you need to do a few things. First you must declare a namespace to find your attributes. You do this on the root layout element. Normally there is only xmlns:android="http://schemas.android.com/apk/res/android". You must now also add xmlns:whatever="http://schemas.android.com/apk/res-auto".
Example:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:whatever="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<org.example.mypackage.MyCustomView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
whatever:my_custom_attribute="Hello, world!" />
</LinearLayout>
Finally, to access that custom attribute you normally do so in the constructor of your custom view as follows.
public MyCustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView, defStyle, 0);
String str = a.getString(R.styleable.MyCustomView_my_custom_attribute);
//do something with str
a.recycle();
}
The end. :)
Qberticus's answer is good, but one useful detail is missing. If you are implementing these in a library replace:
xmlns:whatever="http://schemas.android.com/apk/res/org.example.mypackage"
with:
xmlns:whatever="http://schemas.android.com/apk/res-auto"
Otherwise the application that uses the library will have runtime errors.
The answer above covers everything in great detail, apart from a couple of things.
First, if there are no styles, then the (Context context, AttributeSet attrs) method signature will be used to instantiate the preference. In this case just use context.obtainStyledAttributes(attrs, R.styleable.MyCustomView) to get the TypedArray.
Secondly it does not cover how to deal with plaurals resources (quantity strings). These cannot be dealt with using TypedArray. Here is a code snippet from my SeekBarPreference that sets the summary of the preference formatting its value according to the value of the preference. If the xml for the preference sets android:summary to a text string or a string resouce the value of the preference is formatted into the string (it should have %d in it, to pick up the value). If android:summary is set to a plaurals resource, then that is used to format the result.
// Use your own name space if not using an android resource.
final static private String ANDROID_NS =
"http://schemas.android.com/apk/res/android";
private int pluralResource;
private Resources resources;
private String summary;
public SeekBarPreference(Context context, AttributeSet attrs) {
// ...
TypedArray attributes = context.obtainStyledAttributes(
attrs, R.styleable.SeekBarPreference);
pluralResource = attrs.getAttributeResourceValue(ANDROID_NS, "summary", 0);
if (pluralResource != 0) {
if (! resources.getResourceTypeName(pluralResource).equals("plurals")) {
pluralResource = 0;
}
}
if (pluralResource == 0) {
summary = attributes.getString(
R.styleable.SeekBarPreference_android_summary);
}
attributes.recycle();
}
#Override
public CharSequence getSummary() {
int value = getPersistedInt(defaultValue);
if (pluralResource != 0) {
return resources.getQuantityString(pluralResource, value, value);
}
return (summary == null) ? null : String.format(summary, value);
}
This is just given as an example, however, if you want are tempted to set the summary on the preference screen, then you need to call notifyChanged() in the preference's onDialogClosed method.
The traditional approach is full of boilerplate code and clumsy resource handling. That's why I made the Spyglass framework. To demonstrate how it works, here's an example showing how to make a custom view that displays a String title.
Step 1: Create a custom view class.
public class CustomView extends FrameLayout {
private TextView titleView;
public CustomView(Context context) {
super(context);
init(null, 0, 0);
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, 0, 0);
}
public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs, defStyleAttr, 0);
}
#RequiresApi(21)
public CustomView(
Context context,
AttributeSet attrs,
int defStyleAttr,
int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(attrs, defStyleAttr, defStyleRes);
}
public void setTitle(String title) {
titleView.setText(title);
}
private void init(AttributeSet attrs, int defStyleAttr, int defStyleRes) {
inflate(getContext(), R.layout.custom_view, this);
titleView = findViewById(R.id.title_view);
}
}
Step 2: Define a string attribute in the values/attrs.xml resource file:
<resources>
<declare-styleable name="CustomView">
<attr name="title" format="string"/>
</declare-styleable>
</resources>
Step 3: Apply the #StringHandler annotation to the setTitle method to tell the Spyglass framework to route the attribute value to this method when the view is inflated.
#HandlesString(attributeId = R.styleable.CustomView_title)
public void setTitle(String title) {
titleView.setText(title);
}
Now that your class has a Spyglass annotation, the Spyglass framework will detect it at compile-time and automatically generate the CustomView_SpyglassCompanion class.
Step 4: Use the generated class in the custom view's init method:
private void init(AttributeSet attrs, int defStyleAttr, int defStyleRes) {
inflate(getContext(), R.layout.custom_view, this);
titleView = findViewById(R.id.title_view);
CustomView_SpyglassCompanion
.builder()
.withTarget(this)
.withContext(getContext())
.withAttributeSet(attrs)
.withDefaultStyleAttribute(defStyleAttr)
.withDefaultStyleResource(defStyleRes)
.build()
.callTargetMethodsNow();
}
That's it. Now when you instantiate the class from XML, the Spyglass companion interprets the attributes and makes the required method call. For example, if we inflate the following layout then setTitle will be called with "Hello, World!" as the argument.
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:width="match_parent"
android:height="match_parent">
<com.example.CustomView
android:width="match_parent"
android:height="match_parent"
app:title="Hello, World!"/>
</FrameLayout>
The framework isn't limited to string resources has lots of different annotations for handling other resource types. It also has annotations for defining default values and for passing in placeholder values if your methods have multiple parameters.
Have a look at the Github repo for more information and examples.
if you omit the format attribute from the attr element, you can use it to reference a class from XML layouts.
example from attrs.xml.
Android Studio understands that the class is being referenced from XML
i.e.
Refactor > Rename works
Find Usages works
and so on...
don't specify a format attribute in .../src/main/res/values/attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyCustomView">
....
<attr name="give_me_a_class"/>
....
</declare-styleable>
</resources>
use it in some layout file .../src/main/res/layout/activity__main_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<SomeLayout
xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- make sure to use $ dollar signs for nested classes -->
<MyCustomView
app:give_me_a_class="class.type.name.Outer$Nested/>
<MyCustomView
app:give_me_a_class="class.type.name.AnotherClass/>
</SomeLayout>
parse the class in your view initialization code .../src/main/java/.../MyCustomView.kt
class MyCustomView(
context:Context,
attrs:AttributeSet)
:View(context,attrs)
{
// parse XML attributes
....
private val giveMeAClass:SomeCustomInterface
init
{
context.theme.obtainStyledAttributes(attrs,R.styleable.ColorPreference,0,0).apply()
{
try
{
// very important to use the class loader from the passed-in context
giveMeAClass = context::class.java.classLoader!!
.loadClass(getString(R.styleable.MyCustomView_give_me_a_class))
.newInstance() // instantiate using 0-args constructor
.let {it as SomeCustomInterface}
}
finally
{
recycle()
}
}
}
HERE is the official documentation for creating custom attributes and Views

Categories

Resources