I am creating a gradient using the Linear Gradient in android on a canvas object. I am using this gradient by including the class in my main layout xml. The code generating the gradient is:
public class BackgroundGradient extends View{
private Resources res;
private int [] colors;
private float [] pos;
private Paint paint;
private Shader shader;
public BackgroundGradient(Context context) {
// TODO Auto-generated constructor stub
super(context);
init();
}
public BackgroundGradient(Context context, AttributeSet attrs) {
// TODO Auto-generated constructor stub
super(context,attrs);
init();
}
public BackgroundGradient(Context context, AttributeSet attrs, int defStyle) {
// TODO Auto-generated constructor stub
super(context,attrs,defStyle);
init();
}
private void init() {
paint = new Paint();
res = getResources();
colors = new int[10];
pos = new float[10];
int[] c = { //array of colors };
float[] p = { //positions };
for (int i = 0; i < 8; i++) {
colors[i] = c[i];
pos[i] = p[i];
}
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
this.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
shader = new LinearGradient(0,getHeight(),getWidth(), 0, colors, pos, Shader.TileMode.CLAMP);
paint.setShader(shader);
canvas.rotate(20, 0, getHeight());
canvas.drawPaint(paint);
}
}
So, above is the file that I included in my activity_main.xml inside a frame layout. Content of activity_main :
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<include layout="@layout/bg_gradient" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="5dp"
android:background="#000"
android:orientation="horizontal">
<TextView android:id="@+id/pager_strip"
android:layout_width="100dp"
android:layout_height="5dp"
android:background="@color/mu_blue_6"/>
</LinearLayout>
<!-- other views -->
</FrameLayout>
Content of bg_gradient.xml:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!--
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#000000"
android:text="This is button" /> -->
<in.mubpack.b2o.ui.BackgroundGradient
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</merge>
I cannot figure out why the gradient is visible in some Android devices and not in others. Need help.!!
0 comments:
Post a Comment