Search code examples
androidandroid-layoutandroid-fragmentsandroid-listfragmentandroid-fragmentactivity

How to add image to the listFragment First item only?


I have implemented the fragments in android 4.0.I want to add an image to the list fragment for the first item only.

I have implemented the list fragment as follows:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
     dummyContent = (new listFragmentAdapter<DummyContent.DummyItem>(getActivity(),DummyContent.ITEMS));
setListAdapter(dummyContent);   
    }

and listFragmentAdapter is as follows:

    public listFragmentAdapter(Context context, T[] items) {

            super(context,R.layout.list_fragment_text, items);
            this.ctx = context;

        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            View view = super.getView(position, convertView, parent);
            TextView textView = (TextView) view.findViewById(R.id.cust_view);
            Typeface tf = Typeface.createFromAsset(ctx.getAssets(), "fonts/segoeuil.ttf");
            textView.setTypeface(tf);

            return view;
        }

}

Solution

  • You need to have at least one ImageView in your layout. And then, add/remove your image (drawable/bitmap) at getView() method, something like this:

    LayoutInflater mInflater = LayoutInflater.from(context);
    itemView = mInflater.inflate(R.id.cust_view, null); 
    
    // if first item
    if (position == 0) {
        imageView = (ImageView) itemView.findViewById(R.id.imageViewFirstRow);
        imageView.setImageResource(R.drawable.yourImage);
        imageView.setVisibility(Visible.VISIBLE);
    }
    else {
        // hide/remove image
        imageView.setVisibility(Visible.INVISIBLE); // or GONE, as you wish
    }
    

    Hope this helps.