In this post I will show you how to set your custom layout as the background of your item of your listview or gridview or any other view that contains long list of data, through your adapter.
This is very simple and can be done as follows:
1. Make a file custom_placeholder.xml of your custom layout as follows:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="140dp"
android:layout_height="140dp"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="6dp"
android:background="@drawable/shape_bg">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Downloading..."
android:textAlignment="center"
android:textSize="14sp" />
</RelativeLayout>
</LinearLayout>
2. Now in the getView method of your adapter just replace your code with below code:
public View getView(final int position, View convertView, ViewGroup parent) {
CustomViewHolder mViewHolder;
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.item_gridview_assets, parent, false);
mViewHolder = new CustomViewHolder(convertView); // set your layout (convertView) as your viewHolder
convertView.setTag(mViewHolder);
} else {
mViewHolder = (CustomViewHolder) convertView.getTag();
}
//Now check the condition whether your image is available or not
//Now check the condition whether your image is available or not
String value = imageList.get(position);
if (!value.equalsIgnoreCase("")) {
// case when image is available
// case when image is available
mViewHolder.imgAssets.setBackgroundResource(R.drawable.sample_img);
} else {
// case when image is not available
// case when image is not available
// This will inflate your custom view that you created above
LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.custom_placeholder, parent, false);
}
return convertView;
}
That's all.
Share and comment if any issues.
No comments:
Post a Comment