f分为三步:
1.编写布局文件
如: gradient_background.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="@dimen/leanback_control_panel_shadow_width"
android:layout_height="@dimen/leanback_control_panel_shadow_height"
android:orientation="vertical">
<View
android:layout_width="match_parent"
android:layout_height="@dimen/leanback_control_panel_shadow_top_transparent_height"
android:background="@android:color/transparent"
/>
<View
android:layout_width="match_parent"
android:layout_weight="1"
android:background="@drawable/gradient_background"
android:layout_height="0dp"/>
<View
android:layout_width="match_parent"
android:layout_height="@dimen/leanback_control_panel_shadow_bottom_shadow_height"
android:background="#B3000000"
/>
</LinearLayout>
2.加载layout
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.gradient_background, null);
3.将布局文件转换成Bitmap
private Drawable getDrawableOfView(View view) {
ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(layoutParams.width, View.MeasureSpec.EXACTLY);
int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(layoutParams.height, View.MeasureSpec.EXACTLY);
view.measure(widthMeasureSpec, heightMeasureSpec);
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return new BitmapDrawable(getResources(), bitmap);
}
4.将Drawable 设置为targetView 的背景
mBackgroundView.setBackground(getDrawableOfView(layout));