How to require a view with specified id - android

I want to write a custom view that requires some button with a speicific id to be present (to be able to be found by id), as in ListActivity android.R.id.list must be present, how do i do the same with a custom id of my own?
I plan on reusing this view in an Android lib for several use cases, but all of them must declare some specific view with specific id so that i can find it by id in the lib code and manipulate it for later use in using Applications...

Just do what the ListActivity does.
Check for the ID in your custom view and throw an exception if it does not exist in the layout.
Snippet from ListActivity Source:
#Override
public void onContentChanged() {
super.onContentChanged();
View emptyView = findViewById(com.android.internal.R.id.empty);
mList = (ListView)findViewById(com.android.internal.R.id.list);
if (mList == null) {
throw new RuntimeException(
"Your content must have a ListView whose id attribute is " +
"'android.R.id.list'");
}

The best way to do this is in a flexible way is to use a custom attribute. It allows for any id to be the required id, but it also uses the dev tools to enforce that a valid id is used.
Declare that your custom view is style-able with a custom attribute in an attrs.xml file like this:
<resources>
<declare-styleable name="MyView">
<attr name="required_view_id" format="integer" />
</declare-styleable>
</resources>
You can then refer to the attribute from a layout file like below. Pay special attention to the header where the "app" namespace is defined. You can use any name you want for your custom attribute namespace, but you have to declare it to use any of your custom attributes when defining the views later. Note the custom attribute on MyView.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<View
android:id="#+id/the_id_of_the_required_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<com.full.package.to.MyView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:required_view_id="#id/the_id_of_the_required_view" />
</LinearLayout>
Now you need to make sure this view is present in your custom view class. You can required that your custom attribute is set by overriding certain constructors. You'll also need to actually verify the presence of the required view at some point. Here's a rough idea:
public class MyView extends View {
private int mRequiredId;
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
checkForRequiredViewAttr(context, attrs);
}
public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
checkForRequiredViewAttr(context, attrs);
}
// Verify that the required id attribute was set
private void checkForRequiredViewAttr(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.MyView, 0, 0);
mRequiredId = a.getResourceId(R.styleable.MyView_required_view_id, -1);
a.recycle();
if (mRequiredId == -1) {
throw new RuntimeException("No required view id attribute was set");
}
}
// This allows the custom view to be programmatically instantiated, so long as
// the required id is manually set before adding it to a layout
public void setRequiredId(int id) {
mRequiredId = id;
}
// Check for the existence of a view with the required id
#Override
protected void onAttachedToWindow() {
View root = getRootView();
View requiredView = root.findViewById(mRequiredId);
if (requiredView == null) {
throw new RuntimeException(
String.format("Cannot find view in layout with id of %s", mRequiredId));
}
super.onAttachedToWindow();
}
}
Using onAttachedToWindow to check for the required view may not be good enough for your purposes. It won't, for example, prevent the required view from being removed. Finding a view in a layout isn't a cheap operation, especially for complex layouts, so you shouldn't constantly check for 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 :)

How to pass custom attributes to nested xml

I have structure like that:
preferences.xml:
...
<com.example.MyCustomPreference
...
myCustomMessage="#string/abc"
android:inputType="..."
... />
...
preference_my_custom.xml:
<LinearLayout ...>
<com.example.MyCustomView
...
app:myCustomMessage="?????"
... />
</LinearLayout>
view_my_custom.xml:
<GridView ...>
...EditTexts, TextViews, etc.
</GridView>
I would like to pass myCustomMessage's value (I omitted other attributes for simplification) from MyCustomPreference to MyCustomView using XML. MyCustomView reads custom attributes, so I would like to avoid reading attributes in MyCustomPreference programmatically, getting TextViews from MyCustomView and setting them values. However, I really don't know what to type in place of "?????".
How can i do this using XML? Is this possible?
You have to do it programmatically (unless you use data binding). For example, in your MyCustomPreference you catch de attribute myCustomMessage:
String myCustomMessage = null;
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyCustomPreference, 0, 0);
try {
myCustomMessage = a.getString(R.styleable.MyCustomPreference_myCustomMessage);
} finally {
a.recycle();
}
Here you got the String value of your attribute. Then, I supose you have inflated your MyCustomView inside your MyCustomPreference. As an example:
View.inflate(getContext(), R.layout.preference_my_custom, this);
MyCustomView myCustomView = (MyCustomView) findViewById(R.id.you_custom_view_id);
So, here you can set programmatically your myCustomMessage in your MyCustomView.
myCustomView.setMyCustomMessage(myCustomMessage);
You should create this method to set correctly your text, and if necessary propagate this text to other child views of your MyCustomView.
Now, changing your String resId in your preferences.xml the interface should update as expected.
P.S: Since I don't know all your resource ids, please adapt them to your project.
Create an attribute file for your customeView:
Add in attrs.xml
<declare-styleable name="CustomView">
<attr name="width" format="dimension" />
</declare-styleable>
Used in your customView init:
public CustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView, defStyle, 0);
mWidth = a.getDimensionPixelSize(R.styleable.CustomView_width,0);
a.recycle();
}

Android custom image view using built-in attributes

It's my very first question here, so please go easy on me ;)
I've built my custom View class extending ImageView.
public class CustomImageView extends ImageView {
// ...
}
I have created a set of custom parameters for it in the shape of a <declare-styleable> item in the attrs.xml file.
<declare-styleable name="CustomImageView">
<attr name="angle" format="integer"/>
</declare-styleable>
I've figured out how to access (i.e. read from within the class and set from within the layout) these values.
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomImageView, 0, 0);
try {
a.getInt(R.styleable.CustomImageView_angle, 0);
} finally {
a.recycle();
}
So far, so easy. All of the above are directly taken from the guide.
However, I could not figure out how to access the inherited attributes of the ImageView class. Specifically, I want to read what was set as the src attribute of the ImageView. I'm assuming I have to use a different value for the second parameter of the obtainStyledAttributes(...) call, but I don't know what to use there and this obviously does not work:
a = context.getTheme().obtainStyledAttributes(attrs, ImageView, 0, 0);
So, how do I access the built-in attributes of my super class?
How do I get the int value (drawable res id) that was set for the android:src attribute?
Thanks for your help!
How do I get the int value (drawable res id) that was set for the
android:src attribute?
Use getAttributeResourceValue to get id of drawable :
public CustomImageView(Context context, AttributeSet attrs) {
super(context, attrs);
String android_schemas = "http://schemas.android.com/apk/res/android";
int srcId = attrs.getAttributeResourceValue(android_schemas, "src", -1);
}

Alter AttributeSet values in android

I am having custom view which will take attribute set(xml value) as constructor value
public CustomView(Context context) // No Attributes in this one.
{
super(context);
this(context, null, 0);
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
this(context, attrs, 0)
}
public CustomView(Context context, AttributeSet attrs, int default_style) {
super(context, attrs, default_style);
readAttrs(context, attrs, defStyle);
init();
}
In Fragment class i am setting the view as
CustomView customView = (CustomView) view.findViewById(R.id.customView);
where custom view contains various value such as height,width,padding etc.
i want to modify those values based on required condition and set it back to custom view.
I placed setting width height code in onDraw method and called invalidte view.
But above method will set the every time if i called invalidate method in CustomView class.
how to overcome this so that i can pass modified attribute set value in constructor only.?
Edit: I need to modify the view values(initialize with new values) which is set during attribute constructor so that i will get a refreshed view with a new values.
Override #OnDraw or 'Invalidate' is not a good function for me where inside invalidate i have written the methods which will execute in each second interval.
I see that your CustomView can have multiple attributes and you want to modify some of these attributes based on some condition and pass this in the constructor.
Few best practices while designing a custom view:
If you have custom attributes, make sure that you expose them via setters and getters. In your setter method, call invalidate();
Don't try modifying any attributes inside onDraw() or onMeasure() methods.
Try your best to avoid writing Custom constructors for your Custom View.
So the ideal way to solve your problem is to instantiate your CustomView and then modify the attributes, either externally (in your Activity or Fragment), or have a method inside the CustomView.java and then invoke it externally. Doing this will still give you the same result you are looking for.
So lets say you declared your custom attributes like this for view named StarsView
<declare-styleable name="StarsView">
<attr name="stars" format="integer" />
<attr name="score" format="float" />
</declare-styleable>
And you want to read attributes from something like this
<my.package..StarsView
app:stars="5"
app:score="4.6"
You do just this in constructor
public StarsView(Context context, AttributeSet attrs) {
super(context, attrs);
if(attrs != null) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.StarsView, defStyleAttr, 0);
stars = Tools.MathEx.clamp(1, 10, a.getInt(R.styleable.StarsView_stars, 5));
score = (int)Math.floor(a.getFloat(R.styleable.StarsView_score, stars) * 2f);
a.recycle(); // its important to call recycle after we are done
}
}
It's probably not the solution you were hoping for, but put a FrameLayout in your xml instead of the CustomView, and then create your CustomView programmatically with the FrameLayout as it's parent

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