以编程方式覆盖图像
问题描述:
我正在尝试使用图像,透明渐变叠加和textView来实现一个gridView,因此无论图像的颜色如何,文本总是可读的。我无法添加叠加层和TextView。我在另一个问题中读到,RelativeLayouts是叠加的方式,然后为渐变XML文件设置RelativeLayout背景。这是我到目前为止。以编程方式覆盖图像
public class GridViewAdapter extends BaseAdapter {
private Context mContext;
public GridViewAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
RelativeLayout gradient;
TextView textView;
DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
int screenWidth = metrics.widthPixels;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(screenWidth/2, screenWidth/2));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
gradient = new RelativeLayout(mContext);
gradient.setBackground(mContext.getResources().getDrawable(R.drawable.gridview_gradient_image_overlay));
gradient.setLayoutParams(new GridView.LayoutParams(screenWidth/2, screenWidth/2));
} else {
imageView = (ImageView) convertView;
gradient = (RelativeLayout) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// references to images
private Integer[] mThumbIds = {
R.drawable.dog, R.drawable.cat,
R.drawable.horse, R.drawable.bunny,
R.drawable.fish, R.drawable.hamster,
R.drawable.hedgehog, R.drawable.bird,
R.drawable.turtle, R.drawable.goat
};
}
这是梯度XML文件:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:startColor="#33000000"
android:centerColor="#11000000"
android:endColor="#00000000"
android:angle="90"
android:dither="true"
/>
</shape>
XML布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rlGradient"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/gridview_gradient_image_overlay">
<TextView
android:id="@+id/tvGridViewAnimal"
android:layout_width="10dp"
android:layout_height="10dp"
android:textColor="#ffffff"/>
</RelativeLayout>
答
为了改变基于XML-Z顺序,只需调用方法bringToFront()
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
//...
textView.bringToFront();
return imageView;
}
不能使用谷歌? –
这是一个很常见的问题 –
发布您的XML布局,这是一个z顺序问题 – bonnyz