How to set custom font for TabLayout in Android? - android

I want use TabLayout and ViewPager in my app, but i want set custom font for TabLayout but i can't this!
I use this code :
Typeface droidSerifMonoTF = Typeface.createFromAsset(getAssets(), "fonts/DroidSerif.ttf");
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
TextView t = new TextView(this);
t.setText(mSectionsPagerAdapter.getPageTitle(i) );
t.setTypeface(droidSansMonoTF);
actionBar.addTab(actionBar.newTab()
.setCustomView(t)
.setTabListener(this));
}
from this link : Link but don't work me!
How can i it?

You can do that by extending TabLayout class. Override onLayout method as bellow:
#Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom){
super.onLayout(changed, left, top, right, bottom);
final ViewGroup tabStrip = (ViewGroup)getChildAt(0);
final int tabCount = tabStrip.getChildCount();
ViewGroup tabView;
int tabChildCount;
View tabViewChild;
for(int i=0; i<tabCount; i++){
tabView = (ViewGroup)tabStrip.getChildAt(i);
tabChildCount = tabView.getChildCount();
for(int j=0; j<tabChildCount; j++){
tabViewChild = tabView.getChildAt(j);
if(tabViewChild instanceof AppCompatTextView){
if(fontFace == null){
fontFace = Typeface.createFromAsset(context.getAssets(), context.getString(R.string.IranSans));
}
((TextView) tabViewChild).setTypeface(fontFace, Typeface.BOLD);
}
}
}
}
Must Overwrite onLayout method, because, when you use setupWithViewPager method to bind the TabLayout with the ViewPager, you have to set tabs text either with setText method or in the PagerAdapter after that and when this happened, onLayout method get called on the parent ViewGroup (TabLayout) and that's the place to put setting fontface.(Changing a TextView text cause calling onLayout method of it's parent - A tabView has two children, one is ImageView another is TextView)
Another Solution:
First, these lines of code:
if(fontFace == null){
fontFace = Typeface.createFromAsset(context.getAssets(), context.getString(R.string.IranSans));
}
In above solution, should be written outside of two loops.
But better solution for API >= 16 is using android:fontFamily:
Create a Android Resource Directory named font and copy your desired font to the directory.
Then use these styles:
<style name="tabLayoutTitles">
<item name="android:textColor">#color/white</item>
<item name="android:textSize">#dimen/appFirstFontSize</item>
<item name="android:fontFamily">#font/vazir_bold</item>
</style>
<style name="defaultTabLayout">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">#dimen/defaultTabLayoutHeight</item>
<item name="android:gravity">right</item>
<item name="tabTextAppearance">#style/tabLayoutTitles</item>
<item name="tabSelectedTextColor">#color/white</item>
<item name="tabIndicatorColor">#color/white</item>
<item name="tabIndicatorHeight">#dimen/accomTabIndicatorHeight</item>
<item name="tabMode">fixed</item>
<item name="tabGravity">fill</item>
<item name="tabBackground">#drawable/rectangle_white_ripple</item>
<item name="android:background">#color/colorPrimary</item>
</style>

Related

Get the current ActionBar size

I tried several things before and searched the web, but no answer.
How do I get the current ActionBar size?
I styled my ActionBar like this:
<style name="MusicSlide.Theme.ActionBar" parent="android:Widget.Holo.ActionBar">
<item name="android:height">60dp</item>
<item name="android:actionBarSize">60dp</item>
<item name="android:homeAsUpIndicator">#drawable/ic_drawer</item>
<item name="android:background">#color/complete_transparent</item>
<item name="android:titleTextStyle">#style/MusicSlide.Theme.ActionBar.TitleText</item>
<item name="android:subtitleTextStyle">#style/MusicSlide.Theme.ActionBar.TitleText</item>
</style>
It is transparent.
In my app I implemented a DrawerLayout. I don't want the DrawerLayout to be underneath the ActionBar , so I set the margin of the DrawerLayout:
final TypedArray styledAttributes = mContext.getTheme().obtainStyledAttributes(
new int[] { android.R.attr.actionBarSize });
int actionheight = (int) styledAttributes.getDimension(0, 0);
styledAttributes.recycle();
ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) mDrawerListRight
.getLayoutParams();
mlp.setMargins(0,(actionheight + statbarheight),0,0);
The problem is that android.R.attr.actionBarSize returns the original height of the ActionBar.
How do I get the 60dp I set in my style?
android:actionBarSize isn't an attribute of Widget.ActionBar, this is why you aren't returning the correct value. Add that line to your app's theme, wherever you define android:actionBarStyle.

Changing ActionBar tabs underline color programmatically

I have created the action bar by
ActionBar actionbar = getActionBar()
The background of the action bar is changed by
actionbar.setBackgroundDrawable(actionBarBackgroundImage);
Now I need to change the action bar tabs underline color programmatically. Is there any method to change the action bar tabs underline color?
Alternatively you could use Android Action Bar Style Generator to easily theme your action bar and tabs.
Here is a much easier way. I know you were looking for a programmatic change, but this one is REALLY easy.
I've been struggling with this for days, but finally found the solution. I'm using AppCompat. You can set colorAccent in your theme and that will change the highlight color on your ActionBar. Like so:
<item name="colorAccent">#color/highlightcolor</item>
Here it is in context:
<style name="LightTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">#color/darkgrey</item>
<item name="colorPrimaryDark">#color/black</item>
<item name="colorAccent">#color/highlightcolor</item>
</style>
Where I originally posted this answer: Android Tab underline color not changing
I'll suggest you use ActionBarSherlock. There is one sample available in the library named "Style ActionBar". (this is only way you can change ActionBar tabs underline color)
if you have customized ActionBar then You have to add this style in ActionBar Style
or here is way how to Do this
create style like below (here i have used ActionBarShareLock if you don't want to use then use android-support-v4.jar for support all Android OS Version)
<style name="Theme.AndroidDevelopers" parent="Theme.Sherlock.Light">
<item name="android:actionBarTabStyle">#style/MyActionBarTabStyle</item>
<item name="actionBarTabStyle">#style/MyActionBarTabStyle</item>
</style>
<!-- style for the tabs -->
<style name="MyActionBarTabStyle" parent="Widget.Sherlock.Light.ActionBar.TabBar">
<item name="android:background">#drawable/actionbar_tab_bg</item>
<item name="android:paddingLeft">32dp</item>
<item name="android:paddingRight">32dp</item>
actionbar_tab_bg.xml
<item android:state_focused="false" android:state_selected="false" android:state_pressed="false" android:drawable="#drawable/ad_tab_unselected_holo" />
<item android:state_focused="false" android:state_selected="true" android:state_pressed="false" android:drawable="#drawable/ad_tab_selected_holo" />
<item android:state_selected="false" android:state_pressed="true" android:drawable="#drawable/ad_tab_selected_pressed_holo" />
<item android:state_selected="true" android:state_pressed="true" android:drawable="#drawable/ad_tab_selected_pressed_holo" />
applay this style in your activity in android manifest file
<activity
android:name="com.example.tabstyle.MainActivity"
android:label="#string/app_name"
android:theme="#style/Theme.AndroidDevelopers" >
for more detail check this answer and this article.
EDITED : 29-09-2015
ActionBarSherlock is deprecated so alternatively you can use android design support library and android app appcompat library for TOOLBAR(Action-Bar is deprecated so..) and TABS.
use TabLayout like below
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="center"
app:tabMode="scrollable"
app:tabSelectedTextColor="#color/white"
app:tabIndicatorColor="#color/colorPrimary"
app:tabIndicatorHeight="2dip"
app:tabTextAppearance="?android:attr/textAppearanceMedium"
app:tabTextColor="#color/colorAccent" />
here is sample of android design support library with tab
Refer this, for customize action bar,
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- the theme applied to the application or activity -->
<style name="CustomActivityTheme" parent="#android:style/Theme.Holo">
<item name="android:actionBarStyle">#style/MyActionBar</item>
<!-- other activity and action bar styles here -->
</style>
<!-- style for the action bar backgrounds -->
<style name="MyActionBar" parent="#android:style/Widget.Holo.ActionBar">
<item name="android:background">#drawable/ab_background</item>
<item name="android:backgroundStacked">#drawable/ab_background</item>
<item name="android:backgroundSplit">#drawable/ab_split_background</item>
</style>
</resources>
I tried many of the suggestions posted here and other places with no luck. But I think I managed to piece together a (albeit not perfect) solution.
The TabWidget is using a selector. Essentially it is showing a different 9 patch image depending on the state of the tab (selected, pressed, etc.). I finally figured out that you could generate a selector programmatically. I started with generated 9 patches from http://android-holo-colors.com/ (color: #727272, TabWidget: Yes).
The biggest issue was setting the color. Setting the color filter did nothing. So, I ended up changing the colors of each of the pixels of the 9 patch image inside a loop.
...
/**
* <code>NinePatchDrawableUtility</code> utility class for manipulating nine patch resources.
*
* #author amossman
*
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class NinePatchDrawableUtility {
// Matches the colors in the supported drawables
private static final int TAB_UNDERLINE_HIGHLIGHT_COLOR = 1417247097;
private static final int TAB_UNDERLINE_COLOR = -8882056;
private static final int TAB_PRESSED_COLOR = -2122745479;
private Resources resources;
public NinePatchDrawableUtility(Resources resources) {
this.resources = resources;
}
/**
* Create a <code>StateListDrawable</code> that can be used as a background for the {#link android.widget.TabWidget}</br></br>
*
* <code>
* FragmentTabHost tabHost = ...</br>
* NinePatchUtility ninePatchUtility = new NinePatchUtility(getResources());</br>
* TabWidget tabWidget = tabHost.getTabWidget();</br>
* for (int i = 0; i < tabWidget.getChildCount(); i++) {</br>
* tabWidget.getChildAt(i).setBackground(ninePatchUtility.getTabStateListDrawable(titleColor));</br>
* }
* </code>
*
* #param tintColor The color to tint the <code>StateListDrawable</code>
* #return A new <code>StateListDrawable</code> that has been tinted to the given color
*/
public StateListDrawable getTabStateListDrawable(int tintColor) {
StateListDrawable states = new StateListDrawable();
states.addState(new int[] {android.R.attr.state_pressed},
changeTabNinePatchColor(resources, R.drawable.cc_tab_selected_pressed_holo, tintColor));
states.addState(new int[] {android.R.attr.state_focused},
changeTabNinePatchColor(resources, R.drawable.cc_tab_selected_focused_holo, tintColor));
states.addState(new int[] {android.R.attr.state_selected},
changeTabNinePatchColor(resources, R.drawable.cc_tab_selected_holo, tintColor));
states.addState(new int[] { },
changeTabNinePatchColor(resources, R.drawable.cc_tab_unselected_holo, tintColor));
return states;
}
/**
* Change the color of the tab indicator.</br></br>
*
* Supports only the following drawables:</br></br>
*
* R.drawable.cc_tab_selected_pressed_holo</br>
* R.drawable.cc_tab_selected_focused_holo</br>
* R.drawable.cc_tab_selected_holo</br>
* R.drawable.cc_tab_unselected_holo</br></br>
*
* Note: This method is not efficient for large <code>Drawable</code> sizes.
*
* #param resources Contains display metrics and image data
* #param drawable The nine patch <code>Drawable</code> for the tab
* #param tintColor The color to tint the <code>Drawable</code>
* #return A new <code>NinePatchDrawable</code> tinted to the given color
*/
public NinePatchDrawable changeTabNinePatchColor(Resources resources, int drawable, int tintColor) {
int a = Color.alpha(tintColor);
int r = Color.red(tintColor);
int g = Color.green(tintColor);
int b = Color.blue(tintColor);
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inMutable = true;
Bitmap bitmap = BitmapFactory.decodeResource(resources, drawable, opt);
for (int x = 0; x < bitmap.getWidth(); x++) {
for (int y = 0; y < bitmap.getHeight(); y++) {
int color = bitmap.getPixel(x, y);
if (color == TAB_PRESSED_COLOR) {
bitmap.setPixel(x, y, Color.argb((int)(a * 0.5), r, g, b));
} else if (color == TAB_UNDERLINE_HIGHLIGHT_COLOR) {
bitmap.setPixel(x, y, Color.argb((int)(a * 0.9), r, g, b));
} else if (color == TAB_UNDERLINE_COLOR) {
bitmap.setPixel(x, y, tintColor);
}
}
}
return new NinePatchDrawable(resources, bitmap, bitmap.getNinePatchChunk(), new Rect(), null);
}
}
Example of usage:
/**
* Theme the tab widget with the defined background color and title color set
* in the TabManager
* #param tabWidget
*/
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
public void theme(TabWidget tabWidget) {
ColorDrawable backgroundDrawable = new ColorDrawable(backgroundColor);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
tabWidget.setBackground(backgroundDrawable);
tabWidget.setAlpha(0.95f);
} else {
backgroundDrawable.setAlpha(242);
tabWidget.setBackgroundDrawable(backgroundDrawable);
}
NinePatchDrawableUtility ninePatchUtility = new NinePatchDrawableUtility(resources);
for (int i = 0; i < tabWidget.getChildCount(); i++) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
tabWidget.getChildAt(i).setBackground(ninePatchUtility.getTabStateListDrawable(titleColor));
} else {
tabWidget.getChildAt(i).setBackgroundDrawable(ninePatchUtility.getTabStateListDrawable(titleColor));
}
View tabView = tabWidget.getChildTabViewAt(i);
tabView.setPadding(0, 0, 0, 0);
TextView tv = (TextView) tabView.findViewById(android.R.id.title);
tv.setSingleLine(); // set the texts on the tabs to be single line
tv.setTextColor(titleColor);
}
}
Got the solution for changing the Tab Highlighter Color after 1 long day of search.Just 2 lines of code makes this work perfect!
Go to values/styles.xml and add the code below in ActionBar Theme
<item name="colorAccent">#color/Tab_Highlighter</item>
Now give the color for Tab_Highlighter in colors.xml
<color name="Tab_Highlighter">#ffffff</color>
you can use this code:
actionBar.setStackedBackgroundDrawable(new ColorDrawable(yourColor));

Remove "Done" button of ActionMode

0I'm using startActionMode(ActionMode) on my app.
By default it's add a "Done" button on the bar, I want to remove it.
Also, if there's a way to change it's text, I want to know too, cause a different description than "Done" can make the action be correspondent to the behaviour of what it does.
I agree with #CommonsWare that it is invalid design to hide the Done button.
However, there are customers that want to have this button removed and I can understand that the checkmark may cause confusion to users because it actually does nothing in some cases.
So, here is how to remove the button with styles:
<style name="AppTheme" parent="android:Theme.Holo">
<item name="android:actionModeCloseButtonStyle">#style/NoCloseButton</item>
</style>
<style name="NoCloseButton" parent="#android:style/Widget.ActionButton.CloseMode">
<item name="android:visibility">gone</item>
</style>
If you are using ActionBarSherlock you can hide the "Done" button with this style:
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="NoCloseButton" parent="#style/Widget.Sherlock.ActionButton.CloseMode">
<item name="android:visibility">gone</item>
</style>
<style name="AppBaseTheme" parent="Theme.Sherlock.Light.DarkActionBar">
<item name="actionModeCloseButtonStyle">#style/NoCloseButton</item>
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
</style>
</resources>
Please make sure to put this style in each style directory (values, value-v11, values-v14). After that you can create a custom menu with this code:
LayoutInflater inflater = LayoutInflater.from(getSherlockActivity());
View actionView = inflater.inflate(R.layout.actionmode, null);
ActionMode am = getSherlockActivity().startActionMode(mActionModeCallback);
am.setCustomView(actionView);
Even I was stuck with same and I found this way to solve it.
int doneButtonId = Resources.getSystem().getIdentifier("action_mode_close_button", "id", "android");
LinearLayout layout = (LinearLayout) findViewById(doneButtonId);
TextView doneview = (TextView) layout.getChildAt(1);
doneview.setText("");
Hope this helps!!
Thanks for Matthias Robbers, it works. But i perfer to use "invisible":
<style name="NoCloseButtonActionModeStyle">
<item name="android:visibility">invisible</item>
</style>
So the custom view position in ActionMode will not indent to parent left.
any one find out screen width solution? – Mayur R. Amipara Jun 5 '15 at 10:27
override your custom view's onMeasure, set it's width to screen width. and in onLayout, relayout your child views.
it works for me.
import android.content.Context;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.RelativeLayout;
import com.android.gallery3d.R;
public class SelectActionModeCustomView extends RelativeLayout {
private View mLeftButton;
private View mRightButton;
private int mScreenWidth;
private static final String TAG = "SelectActionView";
public SelectActionModeCustomView(Context context, AttributeSet attrs) {
super(context, attrs);
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
mScreenWidth = metrics.widthPixels;
}
#Override
protected void onFinishInflate() {
super.onFinishInflate();
mLeftButton = findViewById(R.id.cancel);
mRightButton = findViewById(R.id.select_action);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
this.setMeasuredDimension(mScreenWidth, this.getMeasuredHeight());
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
int childLeft = 0;
int childTop = 0;
childLeft = 0;
childTop = ((b - t) - mLeftButton.getMeasuredHeight()) / 2;
mLeftButton.layout(childLeft, childTop,
childLeft + mLeftButton.getMeasuredWidth(),
childTop + mLeftButton.getMeasuredHeight());
childLeft = (r - l) - mRightButton.getMeasuredWidth();
childTop = ((b - t) - mRightButton.getMeasuredHeight()) / 2;
mRightButton.layout(childLeft, childTop,
childLeft + mRightButton.getMeasuredWidth(),
childTop + mRightButton.getMeasuredHeight());
}
}

setting a max width for my dialog

My dialog is using a linearlayout for its root, and its using the following code as its custom theme:
<style name="HuskyBusDialog">
<item name="android:windowNoTitle">true</item>
<item name="android:windowFrame">#null</item>
<item name="android:windowBackground">#drawable/panel_background</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowContentOverlay">#null</item>
<item name="android:windowAnimationStyle">#android:style/Animation.Dialog</item>
<item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
<item name="android:colorBackgroundCacheHint">#null</item>
</style>
Is it possible to set a max width? Its fine on phones but im trying to optimize it for tablets and they are too big.
The width will be dealt with in the XML for the linear layout, not in the style that you apply to it. Use the android:layout_width tag in XML to specify how wide it could possibly be.
An old question, however no replies are suitable, but you can find some hint here: How to customize the width and height when show an Activity as a Dialog
This helps customize the width and height, but not set the max width and height! To achieve that on an activity using a dialog theme, I had to do a couple of things:
1) set a layout listener to know when the dialog layout is set.
2) Adjust the dialog layout if its size was beyond the desired limit, effectively setting max size
Here is the working snippet I'm currently using, called after setContentView():
getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(
new OnGlobalLayoutListener()
{
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#SuppressWarnings("deprecation")
#Override
public void onGlobalLayout()
{
adjustDialog();
}
});
Now the dialog size adjustment, as a percentage of actual screen size:
private void adjustDialog()
{
Window w = getWindow();
w.setGravity(Gravity.CENTER);
int current_width = w.getDecorView().getWidth();
int current_height = w.getDecorView().getHeight();
WindowManager.LayoutParams lp = w.getAttributes();
DisplayMetrics dm = getResources().getDisplayMetrics();
int max_width = (int) (dm.widthPixels * 0.90);
int max_height = (int) (dm.heightPixels * 0.90);
if (current_width > max_width)
{
lp.width = max_width;
}
if (current_height > max_height)
{
lp.height = max_height;
}
w.setAttributes(lp);
}
yeaa if u wanna do with Widht GO for ur xml
and try to do
android:layout_width="Defined in pixels//20px"
or u can try this also
android:width="Defined in pixels// 30px"
i hope it will be hepful to u

Code equivalent of android:cropToPadding

In my android app, I create thumbnails in xml this way:
<ImageView android:id="#+id/my_thumbnail
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#color/white"
android:padding="2dp"
android:scaleType="fitXY"
android:cropToPadding="true" />
This creates a white border around the thumbnail - and looks quite nice.
Now, in another place in the code I need to create the thumbnails in the code, not XML (this is an Adapter class for GridView - to create a grid of thumbnails). I can set all parameters as required, however I cannot find a way to set the cropToPadding in the code. As a result, the thumbnail are drawn over the padding and it looks really ugly.
How do I set this cropToPadding thing in the code?
BTW, the app must work on Android 1.6.
Edit
Following a suggestion from userSeven7s, I add this style to my XML containing other styles:
<style name="GridImage">
<item name="android:background">#color/white</item>
<item name="android:padding">2dp</item>
<item name="android:cropToPadding">true</item>
<item name="android:typeface">monospace</item>
</style>
(Note that the file contains <resources> root element and contains a couple of other <style> elements. Yet all of the other ones are only referenced form layout xml files.)
I then added this code inside my grid view adapter:
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
XmlPullParser parser = mContext.getResources().getXml(R.style.GridImage);
AttributeSet attributes = Xml.asAttributeSet(parser);
imageView = new ImageView(mContext, attributes);
// ... some more initialisation
} else {
imageView = (ImageView) convertView;
}
// ... code to create the bitmap and set it into the ImageView goes here
}
This compiles fine (i.e. R.style.GridImage exists). However when I run this code, the app crashes with Resources.NotFoundException on getXml(R.style.GridImage).
Any suggestions?
If you try the solution with AttributeSet and attributes.getAttributeCount() always returns 0, then just about the only solution left is this hack using reflection:
Field field = ImageView.class.getDeclaredField("mCropToPadding");
field.setAccessible(true);
field.set(imageView, true);
Using this you probably can't be sure it will work in other android firmware versions.
Anyway the missing setter is probably just forgotten, so that justifies the hack for me.
You can get the thumbnails from the ImageView itself. Call getDrawingCache() on each imageview to get the bitmap used for drawing.
new Update :
Create a xml myimage_attrs.xml in xml folder and add all the imageview attributes you need to it.
<?xml version=”1.0″ encoding=”utf-8″?>
<item name=”android:layout_height”>10dp</item>
<item name=”android:layout_width”>10dp</item>
<item name="android:background">#color/white</item>
<item name="android:padding">2dp</item>
<item name="android:cropToPadding">true</item>
<item name="android:typeface">monospace</item>
....
Then create a AttributeSet out of the xml and pass it to the ImageView constructor.
XmlPullParser parser = resources.getXml(R.xml.myimage_attrs);
AttributeSet attributes = Xml.asAttributeSet(parser);
ImageView imgv = new ImageView(context, attributes);
For the benefit of others, here's what finally did work (thanks to userSeven7s for pushing me in the right direction).
I created grid_image.xml file with the following content:
<?xml version="1.0" encoding="utf-8"?>
<style>
<item name="android:layout_height">50dp</item>
<item name="android:layout_width">50dp</item>
<item name="android:background">#color/white</item>
<item name="android:padding">2dp</item>
<item name="android:cropToPadding">true</item>
<item name="android:scaleType">fitXY</item>
</style>
Then in my Adapter for the grid view, I put the following code:
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
XmlPullParser parser = mContext.getResources().getXml(R.xml.grid_image);
AttributeSet attributes = null;
int state = XmlPullParser.END_DOCUMENT;
do {
try {
state = parser.next();
if (state == XmlPullParser.START_TAG) {
if (parser.getName().equals("style")) {
attributes = Xml.asAttributeSet(parser);
break;
}
}
} catch (Exception ignore) {
//ignore it - can't do much anyway
} while(state != XmlPullParser.END_DOCUMENT);
if(attributes == null)
imageView = new ImageView(mContext);
else
imageView = new ImageView(mContext, attributes);
//the rest of initialisation goes here
} else {
imageView = (ImageView) convertView;
}
//set image into the imageview here
return imageView;
}

Categories

Resources