I'd like to define custom attributes in Android fragment using XML (without using bundle additional parameters) like declare-styleable in custom controls. But there are no constructors with AttrSet parameters, so is it possible? Can i just override public void onInflate(android.app.Activity activity, android.util.AttributeSet attrs, android.os.Bundle savedInstanceState) in order to get attributes support?
The Link for Support4Demos is changed or can be changed so posting the complete solution. Here it goes.
Create attrs.xml file in res/values folder. Or add the below content if file already exists.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyFragment">
<attr name="my_string" format="string"/>
<attr name="my_integer" format="integer"/>
</declare-styleable>
Override the onInflate delegate of fragment and read attributes in it
/**
* Parse attributes during inflation from a view hierarchy into the
* arguments we handle.
*/
#Override
public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) {
super.onInflate(activity, attrs, savedInstanceState);
Log.v(TAG,"onInflate called");
TypedArray a = activity.obtainStyledAttributes(attrs,R.styleable.MyFragment);
CharSequence myString = a.getText(R.styleable.MyFragment_my_string);
if(myString != null) {
Log.v(TAG, "My String Received : " + myString.toString());
}
int myInteger = a.getInt(R.styleable.AdFragment_my_integer, -1);
if(myInteger != -1) {
Log.v(TAG,"My Integer Received :" + myInteger);
}
a.recycle();
}
Pass these attributes in your layout file as following. Just an example
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is android activity" />
<fragment
android:id="#+id/ad_fragment"
android:name="com.yourapp.packagename.MyFragment"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
app:my_string="Hello This is HardCoded String. Don't use me"
app:my_integer="30" />
</RelativeLayout>
Thats all. Its a working solution.
While doing this if you see any namespace error in xml.
try project cleaning again and again.
This is pathetic but Eclipse and adt misbehaves sometimes.
#Override
public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) {
super.onInflate(activity, attrs, savedInstanceState);
// Your code here to process the attributes
}
Related
I would like to set a custom attribute (in this case, app:unfocusColor) to the value of another attribute (e.g app:cardBackgroundColor), is this possible?
I try the below method, but has error
<android.support.v7.widget.CardView
.....
app:cardBackgroundColor="#android:color/holo_blue_bright"
app:unfocusColor="#{app:cardBackgroundColor}"
>
yes you can!
for example
create res/valuesmyattr.xml
use this code as content
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="myatt">
<attr name="viewName" format="string"/>
</declare-styleable>
</resources>
in your activity use this code
#Override
protected void onCreate(Bundle savedInstanceState) {
getLayoutInflater().setFactory(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
int id =attrs.getAttributeResourceValue("http://schemas.android.com/apk/res/android","id",-1);
if (id == R.id.specialViewId) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.myatt);
String viewName = typedArray.getString(R.styleable.myatt_viewName);
}
return super.onCreateView(parent, name, context, attrs);
}
and your view should lookalike this
<TextView
app:number="1"
android:id="#+id/specialViewId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:ignore="MissingPrefix"></TextView>
finally if you want use this with out overriding activity you can use LayourInflaterFactory interface
I want to implement a SeekBar that automatically updates a TextView, for the actual value, the maximum value and a minimum value. I derive from SeekBar and define 3 named attributes with the format being reference.
In the constructor, I get a TypedArray by calling obtainStyledAttributes(). TypedArray contains a lot of getters for every kind of attribute types. What I am missing is some kind of Object getReference() or int getReferenceId().
How do I obtain the value for a reference attribute?
Edit:
I have an attribute definition for a class MinMaxSlider, that looks like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MinMaxSlider">
<attr name="min" format="integer" />
<attr name="valueView" format="reference" />
</declare-styleable>
</resources>
a snipped out of the layout definition looks like this:
<LinearLayout
style="#style/ParameterLabelLayout"
android:orientation="horizontal">
<TextView
style="#style/ParameterSliderLabel"
android:text="min. Interval" />
<TextView
android:id="#+id/min_connection_interval_slider_value"
style="#style/ParameterSliderValue"/>
</LinearLayout>
<com.roche.rcpclient.MinMaxSlider
style="#style/ParameterSlider"
android:id="#+id/min_connection_interval_slider"
android:max="3200"
custom:valueView="#id/min_connection_interval_slider_value"
custom:min="1"/>
Here, the MinMaxSlider should reference one of the TextViews above to display its current value there.
From within the constructor of MinMaxSlider, I can lookup the min attributes value.
If I try to lookup the valueView attribute as an integer, I always get the default value (0), not R.id.min_connection_interval_slider as I would expect.
Edit: the right function to lookup a reference seems to be getResourceId. The obtained integer id can be used to use findViewById later, when the overall object hierarchy is constructed.
In my case, I register an OnSeekBarChangeListener() and lookup the View in the callback, when the callback is fired.
You can't receive reference via findViewById in constructor. Because it is not attached to layout yet.
Reference: https://developer.android.com/training/custom-views/create-view.html#applyattr
When a view 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 AttributeSet. Although it's possible to read
values from the AttributeSet directly, doing so has some
disadvantages:
Resource references within attribute values are not resolved Styles
are not applied Instead, pass the AttributeSet to
obtainStyledAttributes(). This method passes back a TypedArray array
of values that have already been dereferenced and styled.
You can receive in another methods.
For example:
attrs.xml
<declare-styleable name="CustomTextView">
<attr name="viewPart" format="reference"></attr>
</declare-styleable>
yourLayout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:gravity="center_vertical"
android:orientation="horizontal">
<tr.com.ui.utils.CustomTextView
android:id="#+id/chat_msg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|bottom"
android:focusableInTouchMode="false"
android:gravity="left"
android:text="test"
app:viewPart="#id/date_view" />
<TextView
android:id="#+id/date_view"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:gravity="right" />
</LinearLayout>
CustomTextView.java
public class CustomTextView extends TextView {
private View viewPart;
private int viewPartRef;
public CustomTextView(Context context) {
super(context);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomTextView, 0, 0);
try {
viewPartRef = a.getResourceId(R.styleable.CustomTextView_viewPart, -1);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
viewPart = ((View) this.getParent()).findViewById(viewPartRef);
}
public View getViewPart() {
return viewPart;
}
public void setViewPart(View viewPart) {
this.viewPart = viewPart;
}}
You can decide your scenario and modify this code.
I would like to create a custom linear layout (to work as some basic list) which accepts a custom parameter from xml, like this:
<MyLinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
myns:layout_to_inflate="#layout/list_item"/>
Then, use it in the constructor:
String layoutToInflate = attrs.getAttributeValue(NAMESPACE, "layout_to_inflate");
I get "#layout/list_item". It is not resolved by the system into the int value which is accessible in R.layout.list_item.
Sure I can parse it and use Resources.getIdentifier to look up the ID, then inflate it, but I think that is not the way.
Then... what is the way? Can I get the system to resolve it directly into the int?
UPDATE:
list_item.xml:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Text here!" />
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myns="http://com.example.layoutinflate"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<com.example.layoutinflate.MyLinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
myns:layout_to_inflate="#layout/list_item" />
</RelativeLayout>
Contents MyLinearLayout.java:
public class MyLinearLayout extends LinearLayout {
private static final String TAG = MyLinearLayout.class.getSimpleName();
public MyLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray styledAttributes = context.obtainStyledAttributes(attrs, R.styleable.MyLinearLayout);
int layoutId = styledAttributes.getResourceId(R.styleable.MyLinearLayout_layout_to_inflate, -1);
int layoutIdInt = styledAttributes.getInt(R.styleable.MyLinearLayout_layout_to_inflate, -1);
String str = styledAttributes.getString(R.styleable.MyLinearLayout_layout_to_inflate);
Log.d(TAG, Integer.toString(layoutId) + ";" + str + ";" + layoutIdInt); //-1; null; -1
styledAttributes.recycle();
}
}
Thanks!
Make sure you correctly define this custom attribute inside your attrs.xml. It has to be like this:
<attr name="layout_to_inflate" format="reference" />
<declare-styleable name="MyLinearLayout">
<attr name="layout_to_inflate" />
</declare-styleable>
Then you can get this value inside your MyLinearLayout object with this:
int layoutToInflateId = attributes.getResourceId(R.styleable.MyLinearLayout_layout_to_inflate, R.layout.<default_layout_to_inflate>);
Recently I've faced with adding custom xml parameters to my views in xml layout. I know that I should use attrs.xml file for this purpose, but... I have found, that I can use custom parameters without any attrs.xml file at all. Can somebody explain this ? Is this a bug or is this a valid case ?
here is my custom view:
public class TestView extends View {
public TestView(final Context context, final AttributeSet attrs) {
this(context, attrs, 0);
}
public TestView(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
final String scheme = "http://red.com/ui/scheme";
if (attrs != null) {
Log.d("TestView", "custom param value: " + attrs.getAttributeValue(scheme, "cutom"));
}
}
}
and here is the main layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:red="http://red.com/ui/scheme"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
<com.red.ui.TestView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffAABBCC"
red:cutom="customvalue"
/>
</LinearLayout>
It is a simple scratch project, created by Android wizard.
The custom attribute that you added is not available in R.java
I think the main motto of making custom attributes is to use it at multiple places.
But through this code we cann't accomplish the same scenario.
Here is the sample code - attrs.xml file
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyLayout">
<attr name="text" format="string" />
</declare-styleable>
</resources>
I am changing main.xml to add the the text attribute
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:red="http://red.com/ui/scheme"
xmlns:myapp="http://schemas.android.com/apk/res/com.psl"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
myapp:text="Text String" />
<com.psl.TestView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffAABBCC"
myapp:text="My Special Text String"
red:cutom="customvalue" />
</LinearLayout>
TestView.java -
public class TestView extends View {
public TestView(final Context context, final AttributeSet attrs) {
this(context, attrs, 0);
}
public TestView(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
final String scheme = "http://red.com/ui/scheme";
if (attrs != null) {
Log.d("TestView", "custom param value: " + attrs.getAttributeValue(scheme, "cutom"));
}
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.MyLayout);
CharSequence s = a.getString(R.styleable.MyLayout_text);
Log.d("MyTestView", "attrs param value: " + s.toString());
}
}
If you noticed after making the attr in attrs.xml. It is available everywhere.
But the attr defined in xml itself through custom namespace is available only through the namespace that you have to define everywhere.
May be its a bug because the attribute is getting added to some custom namespace and not in the application itself.
This is not a "bug" of course. This is how you use a custom view in your xml.
refer to this : http://developer.android.com/guide/topics/ui/custom-components.html
I've got a class that extends a button. I want to add an additional attribute to it. Is there any way to initialize that attribute from XML? For example:
<MyButton android:id="#+id/myBtn" myValue="Hello World"></MyButton>
public class MyButton extends Button{
private String myValue = "";
public CalcButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
}
Yes. You can have custom attributes and assign values to it in XML. You can even assign methods to handle custom events on your widgets. Long press definition at XML layout, like android:onClick does
The needed steps.
Implement your custom widget.
Then add file attrs.xml in res/values/ with following content:
<xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyButton">
<attr name="myValue" format="string"/>
</declare-styleable>
</resources>
Retrieve values from XML in MyButton constructor. Remember to implement all constructors, not only one.
Use new attribute in your layout xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res/**your.package**"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<your.package.MyButton
android:id="#+id/theId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
custom:myValue="myDoSomething"
/>
<!-- Other stuff -->
</LinearLayout>