Search code examples
androidtextviewimageviewandroid-custom-view

combining android components in a custom view


I'm not sure where to start with this, I've been building an app over the last week and have made good progress and need a custom view now. I've looked at http://developer.android.com/guide/topics/ui/custom-components.html. but huh...not sure how to piece it together. I want to position the number picker to the left and some text and an image to the right and be able to listen for clicks on the number picker... To be honest I'm not sure where to start.


Solution

  • I would use a layout to combine your Components. Define your layout in xml:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:orientation="horizontal">
           <NumberPicker
            android:id="@+id/picker"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="1dip"
            android:layout_marginRight="1dip"
            />
           <ImageView 
           android:id="@+id/image"
           android:layout_toRightOf="@id/picker"
           android:src="..."
           android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="1dip"
            android:layout_marginRight="1dip"
           />
          <TextView 
           android:id="@+id/text"
           android:text="some text"
           android:layout_toRightOf="@id/image"
           android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="1dip"
            android:layout_marginRight="1dip"
           />
    </RelativeLayout>
    

    To use this layout as the rows of a list: create a custom list adapter that extends BaseAdapter, set your list adapter to your custom list adapter, and Override the getView method of the adapter with the below:

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    
        View view = null;
    
        //if convertView is null, inflate a view.
        //otherwise reuse the convertView   
        if(convertView == null)
        {
            view = mInflater.inflate(R.layout.filebrowserrow, null);
        }
        else
        {
            view = convertView;
        }
    
        //retrieve picker to set listeners, initialize values, etc  
        NumberPicker picker = (NumberPicker)view.findViewById(R.id.picker);
    
        //retrieve ImageView to change image, etc   
        ImageView image = (ImageView)view.findViewById(R.id.image);
    
        //retrieve TextView to change text, etc 
        TextView text = (TextView)view.findViewById(R.id.text);     
    
        return view;
    

    }