How to set font custom font to Spinner text programmatically? - android

I have a ttf font file in my assets folder. I know how to use it for textviews with:
Typeface externalFont=Typeface.createFromAsset(getAssets(), "fonts/HelveticaNeueLTCom-Lt.ttf");
textview1.setTypeface(externalFont);
I have defined look for my spinner text in it's own xml file (as usuall in android):
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+android:id/text1"
style="?android:attr/spinnerItemStyle"
android:singleLine="true"
android:textColor="#ffffff"
android:gravity="center"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee" />
I just can't reference this textview from code, i always get null pointer exceptions. E.g. i tried:
TextView spinner_text=(TextView)findViewById(R.id.text1);
spinner_text.setTypeface(externalFont);
Is it possible to select my external font even for my spinner text defined in it's own xml?
Thank you.
EDIT with answer:
This works:
String [] items = new String[2];
items[0]="Something1";
items[1]="Something2";
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.spinaca, items) {
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
Typeface externalFont=Typeface.createFromAsset(getAssets(), "fonts/HelveticaNeueLTCom-Lt.ttf");
((TextView) v).setTypeface(externalFont);
return v;
}
public View getDropDownView(int position, View convertView, ViewGroup parent) {
View v =super.getDropDownView(position, convertView, parent);
Typeface externalFont=Typeface.createFromAsset(getAssets(), "fonts/HelveticaNeueLTCom-Lt.ttf");
((TextView) v).setTypeface(externalFont);
v.setBackgroundColor(Color.GREEN);
return v;
}
};
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
It may be necessary to add
import android.view.ViewGroup;
To your list of imports at the top of your file. For some reason Eclipse doesn't make this suggestion when it doesn't recognize the ViewGroup class involved in the code.

This is what worked for me (using ideas both from CommonsWare's and gsanllorente's answers):
private static class MySpinnerAdapter extends ArrayAdapter<String> {
// Initialise custom font, for example:
Typeface font = Typeface.createFromAsset(getContext().getAssets(),
"fonts/Blambot.otf");
// (In reality I used a manager which caches the Typeface objects)
// Typeface font = FontManager.getInstance().getFont(getContext(), BLAMBOT);
private MySpinnerAdapter(Context context, int resource, List<String> items) {
super(context, resource, items);
}
// Affects default (closed) state of the spinner
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView view = (TextView) super.getView(position, convertView, parent);
view.setTypeface(font);
return view;
}
// Affects opened state of the spinner
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
TextView view = (TextView) super.getDropDownView(position, convertView, parent);
view.setTypeface(font);
return view;
}
}
If you, like me, originally populated the Spinner using ArrayAdapter.createFromResource() and an array resource (as in Spinner documentation), then you'd use MySpinnerAdapter like this:
MySpinnerAdapter<String> adapter = new MySpinnerAdapter(
getContext(),
R.layout.view_spinner_item,
Arrays.asList(getResources().getStringArray(R.array.my_array))
);
spinner.setAdapter(adapter);

You would apply the font through your own custom SpinnerAdapter, in getView() and getDropDownView().

If you implement your Adapter in another file, you can access the "getAssets()" function from the constructor of the Adapter, as you have the Context as a parameter.
public class YourItemAdapter extends ArrayAdapter<String> {
int recurso;
Typeface tf;
public YourItemAdapter(Context _context, int _resource,
List<String> _items) {
super(_context, _resource, _items);
recurso=_resource;
tf=Typeface.createFromAsset(_context.getAssets(),"font/digital-7.ttf");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//You can use the new tf here.
TextView spinner_text=(TextView)findViewById(R.id.text1);
spinner_text.setTypeface(tf);
}
}

Try this create custom custom_spinner.xml
<?xml version="1.0" encoding="utf-8"?>
<com.xxxx.xxxx.CheckedTextViewC
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
style="?android:attr/spinnerDropDownItemStyle"
android:singleLine="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:textAlignment="center"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:textSize="18sp"
/>
Create custom CheckedtextView like this
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.CheckedTextView;
public class CheckedTextViewC extends CheckedTextView {
public CheckedTextViewC(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public CheckedTextViewC(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public CheckedTextViewC(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public void setTypeface(Typeface tf, int style) {
if(!this.isInEditMode()){
Typeface normalTypeface = Typeface.createFromAsset(getContext().getAssets(), "font/Roboto-Light.ttf");
Typeface boldTypeface = Typeface.createFromAsset(getContext().getAssets(), "font/Roboto-Light.ttf");
if (style == Typeface.BOLD) {
super.setTypeface(boldTypeface/*, -1*/);
} else {
super.setTypeface(normalTypeface/*, -1*/);
}
}
}
}
implemente the new layout
adapter= new ArrayAdapter <String>(Menu.this,R.layout.custom_spinner, list);

This is the continuation of my previous answer: https://stackoverflow.com/a/51100507/787399
For the compatibility reasons, you can use the styles and customized
classes against the widgets in Android. Although above Android level
15, new /res/font resource folders were introduced:
Font Resources in Android
Step 1: declare item_spinner.xml
<?xml version="1.0" encoding="utf-8"?>
<com.my_package.custom_views.FontTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tv_spinner"
style="#style/App_TextViewStyleSmall"
android:layout_gravity="start|bottom"
android:layout_marginLeft="#dimen/dp_5"
android:layout_marginStart="#dimen/dp_5"
android:ellipsize="marquee"
android:gravity="start|bottom"
android:padding="#dimen/dp_10"
android:singleLine="true"
android:textAlignment="inherit" />
<!--declared in layout: item_spinner.xml-->
<!-- removed attributes: android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/text_grey_light"
android:textSize="#dimen/sp_14" -->
<!--style="?android:attr/spinnerItemStyle"-->
step 2: declare item_spinner_dropdown.xml:
<?xml version="1.0" encoding="utf-8"?>
<com.my_package.custom_views.FontTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tv_spinner"
style="#style/App_TextViewStyleSmall"
android:layout_gravity="start|bottom"
android:layout_marginLeft="#dimen/dp_5"
android:layout_marginStart="#dimen/dp_5"
android:ellipsize="marquee"
android:gravity="start|bottom"
android:padding="#dimen/dp_10"
android:singleLine="true" />
<!--declared in layout: item_spinner_dropdown.xml -->
<!--removed: ?android:attr/dropdownListPreferredItemHeight-->
<!--style="?android:attr/spinnerDropDownItemStyle"-->
Step 3: Use spinner in layout:
<LinearLayout
android:id="#+id/ll_my_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/fet_bus_entity"
android:layout_marginTop="#dimen/dp_12"
android:orientation="horizontal">
<com.my_package.custom_views.FontTextView
style="#style/App_TextViewStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start|bottom"
android:gravity="start|bottom"
android:text="#string/are_you_a" />
<Spinner
android:id="#+id/sp_my_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/dp_5"
android:layout_marginStart="#dimen/dp_5"
android:layout_gravity="end|bottom"
android:spinnerMode="dropdown" />
</LinearLayout>
[Note: id of the FontTextView is same in both the layouts, spinner item and drop down item]
Step 4: use it in the Activity/Fragment:
private void initSpinnerBusinessType(View rootView) {
String[] ar_dd_bus_type = getResources().getStringArray(R.array.ar_dd_bus_type);
List<String> lst_bus_type = Arrays.asList(ar_dd_bus_type);
ArrayList<String> ar_bus_type = new ArrayList<>(lst_bus_type);
//==
ArrayAdapter<String> adapter = new ArrayAdapter<>(activity, R.layout.item_spinner, R.id.tv_spinner, ar_bus_type);
adapter.setDropDownViewResource(R.layout
.item_spinner_dropdown);
//=========
Spinner sp_my_spinner= rootView.findViewById(R.id.sp_my_spinner);
sp_my_spinner.setAdapter(adapter);
}
[ for further guidance see my other post: https://stackoverflow.com/a/51077569/787399 and https://stackoverflow.com/a/22164007/787399 ]

Please follow basic customization of FontTextView, FontEditView, FontRadioButton, FontCheckBox and FontButton.
[ For the exact answer, after seeing this guide, please see:
https://stackoverflow.com/a/51113022/787399 ]
Use custom FontTextView, in ArrayAdapter item layout, like this:
public class FontEditText extends AppCompatEditText {
// private String FONT = "fonts/roboto_regular.ttf";
public FontEditText(Context context) {
super(context, null);
// setFontFromAsset(context, null, R.style.DefaultFontTextView);
// FONT = getContext().getString(R.string.font_roboto_regular);
}
public FontEditText(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
setFontFromAsset(context, attrs, R.attr.fetFontStyle);
}
public FontEditText(Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setFontFromAsset(context, attrs, defStyleAttr);
}
private void setFontFromAsset(Context context, AttributeSet attrs, int defStyle) {
BaseActivity activity = (BaseActivity)((MyApplication) context.getApplicationContext()).getCurrentActivity();
FontAndLocaleManager fontAndLocaleManager = activity.getFontAndLocaleManager();
fontAndLocaleManager.setFontFromAsset(this, R.styleable.FontEditText, R.styleable.FontEditText_fetFontFace, attrs, defStyle);
}
}
use the code:
public void setFontFromAsset(View view, int[] resViewStyleable, int resStyleableViewFontFace, AttributeSet attrs, int defStyle) {
String strFont = null;
Typeface tfFontFace = null;
String strButton = FontButton.class.getCanonicalName(),
strTextView = FontTextView.class.getCanonicalName(),
strEditText = FontEditText.class.getCanonicalName(),
strView = view.getClass().getCanonicalName();
try {
if (view.isInEditMode()) {
return;
}
//R.string.font_roboto_regular
strFont = context.getString(R.string.font_roboto_regular);
tfFontFace = Typeface.createFromAsset(context.getAssets(), strFont);
//AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes
//R.styleable.FontButton
TypedArray a = context.obtainStyledAttributes(attrs, resViewStyleable, defStyle, 0);
//R.styleable.FontButton_btFontFace
String derivedFont = a.getString(resStyleableViewFontFace);
a.recycle();
//==
try {
if (derivedFont != null) {
Typeface derivedFontFace = Typeface.createFromAsset(context.getAssets(), derivedFont);
if (strView.equals(strButton)) {
((FontButton) view).setTypeface(derivedFontFace);
} else if (strView.equals(strTextView)) {
((FontTextView) view).setTypeface(derivedFontFace);
} else if (strView.equals(strEditText)) {
((FontEditText) view).setTypeface(derivedFontFace);
}
return;
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (strFont != null && tfFontFace != null) {
if (strView.equals(strButton)) {
((FontButton) view).setTypeface(tfFontFace);
} else if (strView.equals(strTextView)) {
((FontTextView) view).setTypeface(tfFontFace);
} else if (strView.equals(strEditText)) {
((FontEditText) view).setTypeface(tfFontFace);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Describe style and attributes in respective xmls:
<!--FontTextView-->
<declare-styleable name="FontTextViewStyle">
<!-- Style of the FontTextView. -->
<attr name="ftvFontStyle" format="reference"/>
</declare-styleable>
<declare-styleable name="FontTextView">
<!-- Font face of FontTextView. -->
<attr name="ftvFontFace" format="reference"/>
</declare-styleable>
and
<!--FontTextView-->
<style name="StyledFontTextView" parent="#android:style/Theme.Light">
<item name="ftvFontStyle">#style/DefaultFontTextView</item>
</style>
<style name="DefaultFontTextView">
<item name="ftvFontFace">#string/font_roboto_regular</item>
</style>
define some more styles:
<style name="App_TextViewStyle" parent="#android:style/Widget.TextView">
<item name="android:textColor">#color/text_grey</item>
<item name="android:textSize">#dimen/sp_20</item>
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
</style>
<style name="App_TextViewStyleMedium" parent="#android:style/Widget.TextView">
<item name="android:textColor">#color/text_hint</item>
<item name="android:textSize">#dimen/sp_18</item>
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
</style>
<style name="App_TextViewStyleSmall" parent="#android:style/Widget.TextView">
<item name="android:textColor">#color/text_grey_light</item>
<item name="android:textSize">#dimen/sp_14</item>
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
</style>
mention fonts in your strings.xml:
...
<string name="font_roboto_regular">fonts/roboto_regular.ttf</string>
...
and use in the layouts saving some code and time:
<com.mypackage.custom_views.FontTextView
style="#style/App_TextViewStyleMedium"
android:layout_gravity="start|bottom"
android:gravity="start|bottom"
app:fetFontFace="#string/font_roboto_regular"
android:text="#string/are_you_a" />
At Android level 16 and above, all this is simplified, because now you can keep TTF and other font resources in /res/font folder, rather than in assets. That removes most of the custom classes, styles and attributes, see:
Font Resources in Android
Happy Coding with style!! :-)

Guys I found an awesome solution, I wrap orignal adapter by helper like
Use this class SpinnerViewHelper and happy progamming with Android
new SpinnerViewHelper((Spinner)view.findViewById(R.id.labelSurveyNumber),(parent, v, position, id) -> UrduFontHelper.set(v));
Lambda expression is used.

Related

How to use typeface (custom fonts) to the selected item in the Spinner [duplicate]

I have a ttf font file in my assets folder. I know how to use it for textviews with:
Typeface externalFont=Typeface.createFromAsset(getAssets(), "fonts/HelveticaNeueLTCom-Lt.ttf");
textview1.setTypeface(externalFont);
I have defined look for my spinner text in it's own xml file (as usuall in android):
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+android:id/text1"
style="?android:attr/spinnerItemStyle"
android:singleLine="true"
android:textColor="#ffffff"
android:gravity="center"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee" />
I just can't reference this textview from code, i always get null pointer exceptions. E.g. i tried:
TextView spinner_text=(TextView)findViewById(R.id.text1);
spinner_text.setTypeface(externalFont);
Is it possible to select my external font even for my spinner text defined in it's own xml?
Thank you.
EDIT with answer:
This works:
String [] items = new String[2];
items[0]="Something1";
items[1]="Something2";
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.spinaca, items) {
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
Typeface externalFont=Typeface.createFromAsset(getAssets(), "fonts/HelveticaNeueLTCom-Lt.ttf");
((TextView) v).setTypeface(externalFont);
return v;
}
public View getDropDownView(int position, View convertView, ViewGroup parent) {
View v =super.getDropDownView(position, convertView, parent);
Typeface externalFont=Typeface.createFromAsset(getAssets(), "fonts/HelveticaNeueLTCom-Lt.ttf");
((TextView) v).setTypeface(externalFont);
v.setBackgroundColor(Color.GREEN);
return v;
}
};
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
It may be necessary to add
import android.view.ViewGroup;
To your list of imports at the top of your file. For some reason Eclipse doesn't make this suggestion when it doesn't recognize the ViewGroup class involved in the code.
This is what worked for me (using ideas both from CommonsWare's and gsanllorente's answers):
private static class MySpinnerAdapter extends ArrayAdapter<String> {
// Initialise custom font, for example:
Typeface font = Typeface.createFromAsset(getContext().getAssets(),
"fonts/Blambot.otf");
// (In reality I used a manager which caches the Typeface objects)
// Typeface font = FontManager.getInstance().getFont(getContext(), BLAMBOT);
private MySpinnerAdapter(Context context, int resource, List<String> items) {
super(context, resource, items);
}
// Affects default (closed) state of the spinner
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView view = (TextView) super.getView(position, convertView, parent);
view.setTypeface(font);
return view;
}
// Affects opened state of the spinner
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
TextView view = (TextView) super.getDropDownView(position, convertView, parent);
view.setTypeface(font);
return view;
}
}
If you, like me, originally populated the Spinner using ArrayAdapter.createFromResource() and an array resource (as in Spinner documentation), then you'd use MySpinnerAdapter like this:
MySpinnerAdapter<String> adapter = new MySpinnerAdapter(
getContext(),
R.layout.view_spinner_item,
Arrays.asList(getResources().getStringArray(R.array.my_array))
);
spinner.setAdapter(adapter);
You would apply the font through your own custom SpinnerAdapter, in getView() and getDropDownView().
If you implement your Adapter in another file, you can access the "getAssets()" function from the constructor of the Adapter, as you have the Context as a parameter.
public class YourItemAdapter extends ArrayAdapter<String> {
int recurso;
Typeface tf;
public YourItemAdapter(Context _context, int _resource,
List<String> _items) {
super(_context, _resource, _items);
recurso=_resource;
tf=Typeface.createFromAsset(_context.getAssets(),"font/digital-7.ttf");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//You can use the new tf here.
TextView spinner_text=(TextView)findViewById(R.id.text1);
spinner_text.setTypeface(tf);
}
}
Try this create custom custom_spinner.xml
<?xml version="1.0" encoding="utf-8"?>
<com.xxxx.xxxx.CheckedTextViewC
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
style="?android:attr/spinnerDropDownItemStyle"
android:singleLine="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:textAlignment="center"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:textSize="18sp"
/>
Create custom CheckedtextView like this
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.CheckedTextView;
public class CheckedTextViewC extends CheckedTextView {
public CheckedTextViewC(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public CheckedTextViewC(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public CheckedTextViewC(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public void setTypeface(Typeface tf, int style) {
if(!this.isInEditMode()){
Typeface normalTypeface = Typeface.createFromAsset(getContext().getAssets(), "font/Roboto-Light.ttf");
Typeface boldTypeface = Typeface.createFromAsset(getContext().getAssets(), "font/Roboto-Light.ttf");
if (style == Typeface.BOLD) {
super.setTypeface(boldTypeface/*, -1*/);
} else {
super.setTypeface(normalTypeface/*, -1*/);
}
}
}
}
implemente the new layout
adapter= new ArrayAdapter <String>(Menu.this,R.layout.custom_spinner, list);
This is the continuation of my previous answer: https://stackoverflow.com/a/51100507/787399
For the compatibility reasons, you can use the styles and customized
classes against the widgets in Android. Although above Android level
15, new /res/font resource folders were introduced:
Font Resources in Android
Step 1: declare item_spinner.xml
<?xml version="1.0" encoding="utf-8"?>
<com.my_package.custom_views.FontTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tv_spinner"
style="#style/App_TextViewStyleSmall"
android:layout_gravity="start|bottom"
android:layout_marginLeft="#dimen/dp_5"
android:layout_marginStart="#dimen/dp_5"
android:ellipsize="marquee"
android:gravity="start|bottom"
android:padding="#dimen/dp_10"
android:singleLine="true"
android:textAlignment="inherit" />
<!--declared in layout: item_spinner.xml-->
<!-- removed attributes: android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/text_grey_light"
android:textSize="#dimen/sp_14" -->
<!--style="?android:attr/spinnerItemStyle"-->
step 2: declare item_spinner_dropdown.xml:
<?xml version="1.0" encoding="utf-8"?>
<com.my_package.custom_views.FontTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tv_spinner"
style="#style/App_TextViewStyleSmall"
android:layout_gravity="start|bottom"
android:layout_marginLeft="#dimen/dp_5"
android:layout_marginStart="#dimen/dp_5"
android:ellipsize="marquee"
android:gravity="start|bottom"
android:padding="#dimen/dp_10"
android:singleLine="true" />
<!--declared in layout: item_spinner_dropdown.xml -->
<!--removed: ?android:attr/dropdownListPreferredItemHeight-->
<!--style="?android:attr/spinnerDropDownItemStyle"-->
Step 3: Use spinner in layout:
<LinearLayout
android:id="#+id/ll_my_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/fet_bus_entity"
android:layout_marginTop="#dimen/dp_12"
android:orientation="horizontal">
<com.my_package.custom_views.FontTextView
style="#style/App_TextViewStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start|bottom"
android:gravity="start|bottom"
android:text="#string/are_you_a" />
<Spinner
android:id="#+id/sp_my_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/dp_5"
android:layout_marginStart="#dimen/dp_5"
android:layout_gravity="end|bottom"
android:spinnerMode="dropdown" />
</LinearLayout>
[Note: id of the FontTextView is same in both the layouts, spinner item and drop down item]
Step 4: use it in the Activity/Fragment:
private void initSpinnerBusinessType(View rootView) {
String[] ar_dd_bus_type = getResources().getStringArray(R.array.ar_dd_bus_type);
List<String> lst_bus_type = Arrays.asList(ar_dd_bus_type);
ArrayList<String> ar_bus_type = new ArrayList<>(lst_bus_type);
//==
ArrayAdapter<String> adapter = new ArrayAdapter<>(activity, R.layout.item_spinner, R.id.tv_spinner, ar_bus_type);
adapter.setDropDownViewResource(R.layout
.item_spinner_dropdown);
//=========
Spinner sp_my_spinner= rootView.findViewById(R.id.sp_my_spinner);
sp_my_spinner.setAdapter(adapter);
}
[ for further guidance see my other post: https://stackoverflow.com/a/51077569/787399 and https://stackoverflow.com/a/22164007/787399 ]
Please follow basic customization of FontTextView, FontEditView, FontRadioButton, FontCheckBox and FontButton.
[ For the exact answer, after seeing this guide, please see:
https://stackoverflow.com/a/51113022/787399 ]
Use custom FontTextView, in ArrayAdapter item layout, like this:
public class FontEditText extends AppCompatEditText {
// private String FONT = "fonts/roboto_regular.ttf";
public FontEditText(Context context) {
super(context, null);
// setFontFromAsset(context, null, R.style.DefaultFontTextView);
// FONT = getContext().getString(R.string.font_roboto_regular);
}
public FontEditText(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
setFontFromAsset(context, attrs, R.attr.fetFontStyle);
}
public FontEditText(Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setFontFromAsset(context, attrs, defStyleAttr);
}
private void setFontFromAsset(Context context, AttributeSet attrs, int defStyle) {
BaseActivity activity = (BaseActivity)((MyApplication) context.getApplicationContext()).getCurrentActivity();
FontAndLocaleManager fontAndLocaleManager = activity.getFontAndLocaleManager();
fontAndLocaleManager.setFontFromAsset(this, R.styleable.FontEditText, R.styleable.FontEditText_fetFontFace, attrs, defStyle);
}
}
use the code:
public void setFontFromAsset(View view, int[] resViewStyleable, int resStyleableViewFontFace, AttributeSet attrs, int defStyle) {
String strFont = null;
Typeface tfFontFace = null;
String strButton = FontButton.class.getCanonicalName(),
strTextView = FontTextView.class.getCanonicalName(),
strEditText = FontEditText.class.getCanonicalName(),
strView = view.getClass().getCanonicalName();
try {
if (view.isInEditMode()) {
return;
}
//R.string.font_roboto_regular
strFont = context.getString(R.string.font_roboto_regular);
tfFontFace = Typeface.createFromAsset(context.getAssets(), strFont);
//AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes
//R.styleable.FontButton
TypedArray a = context.obtainStyledAttributes(attrs, resViewStyleable, defStyle, 0);
//R.styleable.FontButton_btFontFace
String derivedFont = a.getString(resStyleableViewFontFace);
a.recycle();
//==
try {
if (derivedFont != null) {
Typeface derivedFontFace = Typeface.createFromAsset(context.getAssets(), derivedFont);
if (strView.equals(strButton)) {
((FontButton) view).setTypeface(derivedFontFace);
} else if (strView.equals(strTextView)) {
((FontTextView) view).setTypeface(derivedFontFace);
} else if (strView.equals(strEditText)) {
((FontEditText) view).setTypeface(derivedFontFace);
}
return;
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (strFont != null && tfFontFace != null) {
if (strView.equals(strButton)) {
((FontButton) view).setTypeface(tfFontFace);
} else if (strView.equals(strTextView)) {
((FontTextView) view).setTypeface(tfFontFace);
} else if (strView.equals(strEditText)) {
((FontEditText) view).setTypeface(tfFontFace);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Describe style and attributes in respective xmls:
<!--FontTextView-->
<declare-styleable name="FontTextViewStyle">
<!-- Style of the FontTextView. -->
<attr name="ftvFontStyle" format="reference"/>
</declare-styleable>
<declare-styleable name="FontTextView">
<!-- Font face of FontTextView. -->
<attr name="ftvFontFace" format="reference"/>
</declare-styleable>
and
<!--FontTextView-->
<style name="StyledFontTextView" parent="#android:style/Theme.Light">
<item name="ftvFontStyle">#style/DefaultFontTextView</item>
</style>
<style name="DefaultFontTextView">
<item name="ftvFontFace">#string/font_roboto_regular</item>
</style>
define some more styles:
<style name="App_TextViewStyle" parent="#android:style/Widget.TextView">
<item name="android:textColor">#color/text_grey</item>
<item name="android:textSize">#dimen/sp_20</item>
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
</style>
<style name="App_TextViewStyleMedium" parent="#android:style/Widget.TextView">
<item name="android:textColor">#color/text_hint</item>
<item name="android:textSize">#dimen/sp_18</item>
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
</style>
<style name="App_TextViewStyleSmall" parent="#android:style/Widget.TextView">
<item name="android:textColor">#color/text_grey_light</item>
<item name="android:textSize">#dimen/sp_14</item>
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
</style>
mention fonts in your strings.xml:
...
<string name="font_roboto_regular">fonts/roboto_regular.ttf</string>
...
and use in the layouts saving some code and time:
<com.mypackage.custom_views.FontTextView
style="#style/App_TextViewStyleMedium"
android:layout_gravity="start|bottom"
android:gravity="start|bottom"
app:fetFontFace="#string/font_roboto_regular"
android:text="#string/are_you_a" />
At Android level 16 and above, all this is simplified, because now you can keep TTF and other font resources in /res/font folder, rather than in assets. That removes most of the custom classes, styles and attributes, see:
Font Resources in Android
Happy Coding with style!! :-)
Guys I found an awesome solution, I wrap orignal adapter by helper like
Use this class SpinnerViewHelper and happy progamming with Android
new SpinnerViewHelper((Spinner)view.findViewById(R.id.labelSurveyNumber),(parent, v, position, id) -> UrduFontHelper.set(v));
Lambda expression is used.

Show loader on Spinner (Dropdown) when it is fetching data from web service

In the image above, I have shown that when the user touches the drop-down spinner it will call the web api for getting data for the spinner. Then, that moment, I want to show the loader only on the spinner view on the left or right somewhere on the view itself like in the image, rather than on whole screen when it is getting data from the web service dynamically and hide that progress bar later when web service completely hit at the end (Ignore that search bar in image).
Just create an custom adapter for your spinner. Follow the instructions found here How to create Spinner-list using CustomAdapter in android .
Put the loading view in the layout inflated in the getView method in the adapter, and manipulate it via a callback from your async task used for fetching the result.
In this i am showing loader on start button and hiding loader when stop button is pressed so you can use according to your need.So , for this i have made three class CustomSpinner,Spinner_Custom_adapter and Activity class for using it
In main layout file
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="vertical">
<www.your_packagename.com.spinnerwithloaderex.CustomSpinner
android:id="#+id/custm_spnr"
android:layout_width="120dp"
android:layout_height="40dp"
android:layout_centerInParent="true"
android:layout_gravity="center"
android:background="#drawable/dropdown_create_sales"
android:paddingRight="15dp"
android:text="Hello World!" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp">
<Button
android:id="#+id/start_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start" />
<Button
android:id="#+id/stop_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop" />
</LinearLayout>
</LinearLayout>
CustomSpinner class
public class CustomSpinner extends android.support.v7.widget.AppCompatSpinner {
private Spinner_Custom_adapter spinner_custom_adapter;
public CustomSpinner(Context context) {
super(context);
}
public CustomSpinner(Context context, int mode) {
super(context, mode);
}
public CustomSpinner(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomSpinner(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public CustomSpinner(Context context, AttributeSet attrs, int defStyleAttr, int mode) {
super(context, attrs, defStyleAttr, mode);
}
public CustomSpinner(Context context, AttributeSet attrs, int defStyleAttr, int mode, Resources.Theme popupTheme) {
super(context, attrs, defStyleAttr, mode, popupTheme);
}
public void setItems(Activity activity, ArrayList<String> spnr_Arr) {
spinner_custom_adapter = new Spinner_Custom_adapter(activity, spnr_Arr);
setAdapter(spinner_custom_adapter);
}
public Spinner_Custom_adapter getSpinner_custom_adapter() {
return spinner_custom_adapter;
}
public void showLoader() {
setEnabled(false);
spinner_custom_adapter.showLoader(true, true);
}
public void dismissLoader() {
setEnabled(true);
spinner_custom_adapter.showLoader(false, true);
}
}
Custom_Adapter class
public class Spinner_Custom_adapter<T> extends ArrayAdapter<T> {
private LayoutInflater flater;
private ProgressBar spinner_progress;
private TextView txtTitle;
private Boolean showOrNot = false;
Spinner_Custom_adapter(Activity context, ArrayList<T> list) {
super(context, R.layout.loader_spinner_lt, R.id.title, list);
flater = context.getLayoutInflater();
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = flater.inflate(R.layout.loader_spinner_lt, parent, false);
}
Object object = getItem(position);
String rowItem = null;
if (object instanceof String) {
rowItem = (String) object;
}
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
txtTitle.setText(rowItem);
ProgressBar spinner_progress = (ProgressBar) convertView.findViewById(R.id.spinner_progress);
this.txtTitle = txtTitle;
this.spinner_progress = spinner_progress;
showLoader(showOrNot, false);
return convertView;
}
void showLoader(Boolean showOrNot, boolean notifyListOrNot) {
if (txtTitle != null && spinner_progress != null) {
this.showOrNot = showOrNot;
spinner_progress.setVisibility(showOrNot ? View.VISIBLE : View.GONE);
if (notifyListOrNot) {
notifyDataSetChanged();
}
}
}
}
Spinner single view layout xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:gravity="center_vertical"
android:orientation="horizontal">
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/title"
style="?android:attr/spinnerDropDownItemStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toLeftOf="#+id/spinner_progress"
android:ellipsize="end"
android:singleLine="true"
android:text="Strawberry"
android:textColor="#CC0033"
android:textSize="16dp" />
<ProgressBar
android:id="#+id/spinner_progress"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:visibility="gone" />
</RelativeLayout>
and for using it
custm_spnr = (CustomSpinner) findViewById(R.id.custm_spnr);
ArrayList<String> items = new ArrayList<>();
items.add("Abcdefg");
items.add("hijklm");
items.add("nopqr");
items.add("stu");
items.add("vwxyza1b1c1");
items.add("d1e1f11g1h1");
custm_spnr.setItems(MainActivity.this, items);
findViewById(R.id.start_btn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
custm_spnr.showLoader();
}
});
findViewById(R.id.stop_btn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
custm_spnr.dismissLoader();
}
});

Storing data in list items

Ultimately, I want to click an item in a ListView (eventually a recycler list view) and have it transfer an id to the next activity for retrieval from the db.
I have a ListView, fed by a CursorAdapter (subclassed). When I set a breakpoint in CursorAdapter.bindView(), the View passed in is of type TwoItemListItem, so I can't set the id on RecipeListItem, which I believe is what I need to do to pass info to the next activity via ListView.setOnItemClickListener().
In the source activity, I get the list view and set the adapter:
RecipeCursorAdapter adapter = new RecipeCursorAdapter(this, cur);
ListView listView = (ListView) findViewById(R.id.recipe_list_list);
listView.setAdapter(adapter);
RecipeCursorAdapter:
public class RecipeCursorAdapter extends CursorAdapter {
protected LayoutInflater cursorInflator;
public RecipeCursorAdapter(Context context, Cursor cursor){
super(context, cursor, 0);
this.cursorInflator = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
// The newView method is used to inflate a new view and return it,
// you don't bind any data to the view at this point.
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent){
return this.cursorInflator.inflate(R.layout.activity_recipe_list_item, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor){
// Find fields to populate in inflated template
TextView tvTitle = (TextView) view.findViewById(R.id.recipeListItemTitle);
TextView tvSubtitle = (TextView) view.findViewById(R.id.recipeListItemSubtitle);
// Extract properties from cursor
String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
String description = cursor.getString(cursor.getColumnIndexOrThrow("description"));
// Populate fields with extracted properties
tvTitle.setText(name);
tvSubtitle.setText(description);
}
}
activity_recip_list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<TwoLineListItem xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/listPreferredItemHeight"
android:mode="twoLine"
android:orientation="horizontal"
tools:context="com.smadacm.reciperepo.RecipeListItem" >
<TextView
android:id="#+id/recipeListItemTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/recipeListItemSubtitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_below="#id/recipeListItemTitle"
android:layout_alignStart="#id/recipeListItemTitle"
android:textColor="#color/colorListSecondary"
android:textAppearance="?android:attr/textAppearanceListItemSecondary" />
</TwoLineListItem>
RecipeListItem:
public class RecipeListItem extends AppCompatActivity {
protected int itemId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipe_list_item);
}
public void setItemId(int id){
this.itemId = id;
}
public int getItemId(){
return this.itemId;
}
}
I was able to stumble into something functional. I don't know if this is right, and I'm open to being corrected.
In my main activity, I added a listener:
RecipeCursorAdapter adapter = new RecipeCursorAdapter(this, cur);
ListView listView = (ListView) findViewById(R.id.recipe_list_list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
int ii = 0; // A line on which I can set a breakpoint
}
});
I added a new class to extend LinearLayout. This mostly just calls the super class, but also adds methods to set and retrieve arbitrary data:
public class RecipeListItem extends LinearLayout {
protected int recipeId;
public RecipeListItem(Context context) {
super(context, (AttributeSet)null, 0, 0);
}
public RecipeListItem(Context context, AttributeSet attrs) {
super(context, attrs, 0, 0);
}
public RecipeListItem(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr, 0);
}
public RecipeListItem(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public void setRecipeId(int id){
this.recipeId = id;
}
public int getRecipeId(){
return this.recipeId;
}
}
I used the LinearLayout subclass to define the list items:
<com.smadacm.reciperepo.widget.RecipeListItem xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:context="com.smadacm.reciperepo.RecipeListItem" >
<TextView
android:id="#+id/recipeListItemTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/recipeListItemSubtitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_below="#id/recipeListItemTitle"
android:layout_alignStart="#id/recipeListItemTitle"
android:textColor="#color/colorListSecondary"
android:textAppearance="?android:attr/textAppearanceListItemSecondary" />
</com.smadacm.reciperepo.widget.RecipeListItem>
Finally, in my CursorAdapter, I set the id by item:
#Override
public void bindView(View viewRaw, Context context, Cursor cursor){
RecipeListItem view = (RecipeListItem) viewRaw;
// Find fields to populate in inflated template
TextView tvTitle = (TextView) view.findViewById(R.id.recipeListItemTitle);
TextView tvSubtitle = (TextView) view.findViewById(R.id.recipeListItemSubtitle);
// Extract properties from cursor
String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
String description = cursor.getString(cursor.getColumnIndexOrThrow("description"));
int id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
// Populate fields with extracted properties
tvTitle.setText(name);
tvSubtitle.setText(description);
view.setRecipeId(id);
}

Android ListView selection background

Okay I'm going absolutely nuts with this. I have a ListView in mode singleChoice, when I click on it I set it to selected. And I set the background to a drawable with a selector (and I tried many states that could correspond to a selected item). However when I select it the background doesn't change and I dont get why. I visited dozens of forums for this but couldn't get an answer. Here's my code:
The ListView in my activity:
<com.gaetanl.aspa.ui.component.ExtensibleListView
android:id="#+id/payment_billing_address_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/item_selectable"
android:choiceMode="singleChoice"></com.gaetanl.aspa.ui.component.ExtensibleListView>
Its class:
public class ExtensibleListView extends ListView {
public ExtensibleListView(Context context) {
this(context, null);
}
public ExtensibleListView(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.listViewStyle);
}
public ExtensibleListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(this, "item " + position + " selected = " + view.isSelected());
view.setSelected(true);
Log.d(this, "selected = " + view.isSelected());
}
});
}
#Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
The selector:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_activated="true"
android:drawable="#color/colorPrimary" />
<item
android:state_active="true"
android:drawable="#color/colorPrimary" />
<item
android:state_checked="true"
android:drawable="#color/colorPrimary" />
<item
android:state_selected="true"
android:drawable="#color/colorPrimary" />
<item
android:drawable="#android:color/transparent" />
</selector>
Method I:
In your list adapter,create getter and setter methods for position.Then in getView method, compare the position as in below:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item.xml, null);
holder = new ViewHolder(); holder.itemLayout(LinearLyout)convertView.findViewById(R.id.item_layout);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if(position==getPosition()){
holder.itemLayout.setBackgroundColor(ContextCompat.getColor(context,R.color.back_ground_color));
}else{
holder.itemLayout.setBackgroundColor(ContextCompat.getColor(context,R.color.background_unselect));
}
return convertView;
}
public void setPosition(int posit) {
this.position = posit;
}
private int getPosition() {
return this.position;
}
Then in the activity , inside listView's onItemSelected() method: call the adapter's setPositionMethod:
list_view.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
mAdapter.setPosition(i);
mAdapter.notifyDataSetChanged();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Just set the list selector to transparent ..that should do the job.
Method II:
Or may be ,You need a selector like below:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:drawable="#color/color_primary" >
</item>
<item
android:state_focused="true"
android:drawable="#color/color_primary" >
</item>
<item
android:state_selected="true"
android:drawablecolor="#color/color_primary" >
</item>
<item android:color="#color/#color/transparent" >
</item>
</selector>
then put list selector as #drawable/list_selector
But, if that doesn't work then I think you can set the background of item xml layout as
android:background="#drawable/list_selector"
Okay I found the answer. I was stupidly trying to set the ListView background (see code above). What I needed to do was, when creating adapter, to select a view for the items that incorporates variation for selected items. Android has one by default: simple_list_item_single_choice.
So here's the working code:
myListView = ((ListView) findViewById(R.id.listview_id));
ArrayAdapter<String> myAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_single_choice, myList);
myListView.setAdapter(myAdapter);
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setSelected(true);
}
});
And then you have it, a list view with radio buttons on the right that check themselves when you click on em.
And here's the ListView in my layout.xml:
<ListView
android:id="#+id/listview_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:choiceMode="singleChoice">
</ListView>

Spinner (dropdown)item same size as Spinner

can i make the size of my item and especially the dropdownitems the same size as the spinner? They are a little bit smaller at the moment. i want them to fill the whole Spinner.
Can anyone help me?
edit:
it looks like this:
http://image-upload.de/image/vjYswg/cbc92fd3e9.jpg
and i want this:
http://image-upload.de/image/JdVZ5z/1f73d79751.jpg
oh and i have to use API 14, so i can't set dropdownwidth
i have set the dropdownviewresource to the following xml:
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape = "rectangle">
<solid
android:color="#666666" />
<corners
android:radius="3dp" />
</shape>
edit: sry, this was my spinner layout, for dropdown_items i use
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="43dp"
android:orientation="horizontal" >
<ImageView
android:layout_height="30dp"
android:layout_width="30dp"
android:layout_marginRight="5dp"
android:layout_gravity="center_vertical"
android:contentDescription="#layout/spinner_item"
android:src="#drawable/circledsync" />
<de.util.FontDropDownTextView
android:id = "#+id/spinner_dropdown_item_textView"
style="?android:attr/spinnerDropDownItemStyle"
android:singleLine="true"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="0.90"
android:gravity="center_vertical"
android:textColor="#color/spinner_text" />
</LinearLayout>
i also use a custom array adapter:
public class MyArrayAdapter extends ArrayAdapter<String> {
private int myTextId = 0;
private int myDropDownResource;
private int myDropDownTextId;
private int myResource;
private LayoutInflater myInflater;
public MyArrayAdapter(Context context, int textViewResourceId, List<String> names) {
super(context, textViewResourceId, names);
myTextId = myDropDownTextId = textViewResourceId;// remember it, so we can find the real TextView
myInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public MyArrayAdapter(Context context, int layoutId, int textViewResourceId, List<String> names) {
super(context, layoutId, textViewResourceId, names);
myTextId = myDropDownTextId = textViewResourceId;// remember it, so we can find the real TextView
myResource = myDropDownResource = layoutId;
myInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setDropDownViewResource(int resource) {
super.setDropDownViewResource(resource);
myDropDownResource = resource;
}
public void setDropDownViewResource(int resource, int textId) {
super.setDropDownViewResource(resource);
myDropDownResource = resource;
myDropDownTextId = textId;
}
public View getView(int position, View convertView, ViewGroup parent) {
View cell = MyGetView(position, convertView, parent, myResource, myTextId);
setFontForChild(cell);
return cell;
}
public View getDropDownView(int position, View convertView, ViewGroup parent) {
View cell = MyGetView(position, convertView, parent, myDropDownResource, myDropDownTextId);
setFontForChild(cell);
return cell;
}
private void setFontForChild(View layoutCell)
{
View realTextView = layoutCell.findViewById(myTextId);
if(realTextView instanceof TextView)
{
Typeface tf = Typeface.createFromAsset(
getContext().getAssets(),"fonts/calibri.otf");
((TextView)realTextView).setTypeface(tf);
}
//else realTextView is null or is not a TextView.
}
private View MyGetView(int position, View convertView, ViewGroup parent,
int resource, int fieldId) {
View view;
TextView text;
if (convertView == null) {
int res = (resource==0)? fieldId : resource;
view = myInflater.inflate(res, parent, false);
} else {
view = convertView;
}
try {
if (fieldId == 0) {
// If no custom field is assigned, assume the whole resource is a TextView
text = (TextView) view;
} else {
// Otherwise, find the TextView field within the layout
text = (TextView) view.findViewById(fieldId);
}
} catch (ClassCastException e) {
Log.e("ArrayAdapter", "You must supply a resource ID for a TextView");
throw new IllegalStateException(
"ArrayAdapter requires the resource ID to be a TextView", e);
}
String item = getItem(position);
if (item instanceof CharSequence) {
text.setText((CharSequence)item);
} else {
text.setText(item);
}
return view;
}
I got same problem. I changed style of my Spinner:
<item name="android:paddingLeft">0dp</item>
<item name="android:paddingRight">0dp</item>
It resolved my problem.
Try this in java code:
spinner.setPopupBackgroundResource(R.drawable.spinner_style);
And in your spinner_style.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="#ffffff" />
</shape>
Add a call like this:
Spinner spinner = (Spinner)findViewById(...);
spinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Try this in xml file:-
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textSize="14pt"
Use size as per your requirement.
Try with custom Spinner it will solve your problem.
Sample:
Initiate:
spinner.setAdapter(new MyCustomAdapter(AssessmentActivity.this,
R.layout.spinner_test, spinnerData));
In your custom adapter:
public class MyCustomAdapter extends ArrayAdapter<String>{
List<String>draft_filter_array_ = new ArrayList<String>();
public MyCustomAdapter(Context context, int textViewResourceId,
List<String> draft_filter_array) {
super(context, textViewResourceId, draft_filter_array);
draft_filter_array_ = draft_filter_array;
}
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
return getCustomView(position, convertView, parent);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
//return super.getView(position, convertView, parent);
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.spinner_test, parent, false);
TextView label=(TextView)row.findViewById(R.id.weekofday);
label.setText(draft_filter_array_.get(position));
return row;
}
}
And in your spinner_test.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/weekofday"
android:layout_width="match_parent"
android:layout_height="42dp"
android:layout_gravity="center"
android:gravity="center"
android:text="Sunday"
android:textColor="#000000"
android:textSize="18sp"
/>
</LinearLayout>

Categories

Resources