Search code examples
androidlistviewandroid-intentcustom-adapter

Passing image Id to custom listview adapter


How can I pass an Image resource Id to my custom adapter? I have a check box in an activity called routedetails . When the checkbox is checked I want to display a check mark next to that item in the listview. But to do this I need to pass the imageId to the custom adapter. I tried doing it with an intent putExtra. But that does not work.

Heres my RouteDetails.java with the checkbox code

public class RouteDetails extends AppCompatActivity {

ImageView routeImage;
String routeName;
CheckBox routeCheckBox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_route_details);

    //back button for route details view
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);


    ///////checkbox///////////////////////////////////////////
   routeCheckBox = (CheckBox) findViewById(R.id.routeCheckBox);
  //////  final ImageView checkImageView = (ImageView) findViewById(R.id.checkImageView);
    routeCheckBox.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view)
    {
      if (routeCheckBox.isChecked())
      {
          //checkImageView.setImageResource(R.drawable.checkmark);
          Intent check = new Intent(RouteDetails.this,CustomAdapter.class);
          check.putExtra("checkImageResource", R.drawable.checkmark);
          startActivity(check);
        /////////////////////////////////////////////


//sets actionbar title
routeName = getIntent().getExtras().getString("routeName");
getSupportActionBar().setTitle(routeName);

//TextView for route details
final TextView routeDetailsView = (TextView) findViewById(R.id.routeDetailsView);
routeDetailsView.setText(getIntent().getExtras().getCharSequence("route"));

//ImageView for route details
routeImage = (ImageView) findViewById(R.id.routeImage);
final int mImageResource = getIntent().getIntExtra("imageResourceId", 0);
 routeImage.setImageResource(mImageResource);

And here's the custom adapter

  class CustomAdapter extends ArrayAdapter<CharSequence>{

   public CustomAdapter(Context context, CharSequence[] routes) {
    super(context, R.layout.custom_row ,routes);
   }

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

LayoutInflater routeInflater = LayoutInflater.from(getContext());
View customView = convertView;
if(customView == null){customView = routeInflater.inflate(R.layout.custom_row, parent, false);}

CharSequence singleRoute = getItem(position);
TextView routeText = (TextView) customView.findViewById(R.id.routeText);
routeText.setText(singleRoute);

////////trying to set checkmark/////
ImageView checkImageView = (ImageView) customView.findViewById(R.id.checkImageView);
checkImageView.setImageResource(((Activity)    getContext()).getIntent().getIntExtra("checkImageResource",0));
 ////////////////////////////////////////

return customView;
} 

And here's the adapter being used in my main activity

  list view with xml array of routes
final CharSequence[] routeListViewItems = getResources().getTextArray(R.array.routeList);

//custom adapter for list view
ListAdapter routeAdapter = new CustomAdapter(this, routeListViewItems);
final ListView routeListView = (ListView) findViewById(R.id.routeListView);
routeListView.setAdapter(routeAdapter);

Any help would be appreciated


Solution

  • Basically you create two activities. Let say, MyListViewActivity containing a ListView whose items are nothing but custom views which hold an ImageView and a TextView; then a CheckBoxActivity holding the CheckBox elements. When a list item is clicked in MyListViewActivity, you start the CheckboxAtivity using startActivityForResult() method.

    Finaly, in the CheckBoxActivity when a checkBox item is checked its textValue is send back to MyListViewActivity for updating the corresponding imageView. See below code snippets:

    Layout file for MyListViewActivity : activity_my_list_view.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_my_list_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="YourPackageNameHere.MyListViewActivity" >
    
    <ListView
     android:id="@+id/list"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content" >
    </ListView>
    
    </RelativeLayout>
    

    Layout file for custom list item: list_single.xml

    <?xml version="1.0" encoding="utf-8"?>
    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <TableRow>
        <LinearLayout
            android:layout_width="match_parent"
            android:orientation="horizontal">
            <ImageView
                android:id="@+id/img"
                android:layout_width="40dp"
                android:layout_height="40dp"/>
    
            <TextView
                android:id="@+id/txt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                 android:layout_marginLeft="@dimen/activity_horizontal_margin"
                android:layout_gravity="center_horizontal|center_vertical" />
    
        </LinearLayout>
    
    
    </TableRow>
    </TableLayout>
    

    Layout file for CheckBoxActivity: activity_checkbox.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_checkbox"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="YourPackageNameHere.CheckboxActivity">
    
    <CheckBox
        android:text="CheckBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
    
        android:id="@+id/checkBox1" />
    <CheckBox
        android:text="CheckBox2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/checkBox2" />
     </LinearLayout>
    

    code for MyListViewActivity :

    package YourPackageNameHere;
    
    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.ImageView;
    import android.widget.ListView;
    import android.widget.TextView;
    import android.widget.Toast;
    
    public class MyListViewActivity extends AppCompatActivity {
    ImageView img;
    ListView list;
    private static final int MY_REQUEST_CODE= 1;
    String[] itemNames = {
            "Google Plus",
            "Twitter",
            "Windows",
            "Bing",
            "Itunes",
            "Wordpress",
            "Drupal"
    } ;
    Integer[] imageId = {
            R.drawable.ic_home_black_18dp,
            R.drawable.ic_account_circle_black_18dp,
            R.drawable.ic_fingerprint_black_18dp,
            R.drawable.ic_help_black_18dp,
            R.drawable.ic_settings_black_18dp,
            R.drawable.ic_power_settings_new_black_18dp,
            R.drawable.ic_directions_run_black_18dp
    
    };
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_list_view);
    
        CustomList adapter = new CustomList(MyListViewActivity.this, itemNames, imageId);
        list=(ListView)findViewById(R.id.list);
        list.setAdapter(adapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    
                Toast.makeText(MyListViewActivity.this, "You Clicked at " + itemNames[+ position], Toast.LENGTH_SHORT).show();
    
                //get the image that has been clicked
                img= (ImageView) view.findViewById(R.id.img);
    
                //Starting the CheckBoxAtivity for  result
                Intent mIntent = new Intent(getBaseContext(), CheckboxActivity.class);
                startActivityForResult(mIntent, MY_REQUEST_CODE);
            }
        });
    
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    
        if (requestCode == MY_REQUEST_CODE) {
    
            if(resultCode == Activity.RESULT_OK){
                String result=data.getStringExtra("result");
                switch (result){
                    case "CheckBox1":
                        img.setImageResource(R.drawable.ic_gps_fixed_black_18dp);
                        break;
                    case "CheckBox2":
                        img.setImageResource(R.drawable.cast_ic_notification_0);
                        break;
                }
            }
    
        }
    }//onActivityResult
    
    public class CustomList extends ArrayAdapter<String> {
    
        private final Activity context;
        private final String[] itemNames;
        private final Integer[] imageId;
        public CustomList(Activity context, String[] itemNames, Integer[] imageId) {
            super(context, R.layout.list_single, itemNames);
            this.context = context;
            this.itemNames = itemNames;
            this.imageId = imageId;
    
        }
        @Override
        public View getView(int position, View view, ViewGroup parent) {
            LayoutInflater inflater = context.getLayoutInflater();
            View rowView= inflater.inflate(R.layout.list_single, null, true);
            TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
    
            ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
            txtTitle.setText(itemNames[position]);
    
            imageView.setImageResource(imageId[position]);
            return rowView;
        }
    }
    }
    

    code for ChecboxActivity:

    package YourPackageNameHere
    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.widget.CheckBox;
    import android.widget.CompoundButton;
    
    public class CheckboxActivity extends AppCompatActivity {
    
    CheckBox mCheckBox1;
    CheckBox mCheckBox2;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_checkbox);
    
        mCheckBox1 = (CheckBox) findViewById(R.id.checkBox1);
        mCheckBox2 = (CheckBox) findViewById(R.id.checkBox2);
    
        mCheckBox1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(mCheckBox1.isChecked()){
                    sendResultToLisViewActivity((String) mCheckBox1.getText()); //send the text string of mCheckBox1 to MyListViewActivity
                }
            }
        });
    
        mCheckBox2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(mCheckBox2.isChecked()){
                    sendResultToLisViewActivity((String) mCheckBox2.getText()); //send the text string of mCheckBox1 to MyListViewActivity
                }
            }
        });
    
    }
    
    public void sendResultToLisViewActivity(String  mStringExtra){
        Intent returnIntent = new Intent();
        returnIntent.putExtra("result",mStringExtra);
        setResult(Activity.RESULT_OK,returnIntent);
        finish();
    }
    }
    

    Lastly in your MainActivity onCreate() method you start MyListViewActivity as follows:

    Intent i = new Intent(MainActivity.this, MyListViewActivity.class);
    startActivity(i);
    

    Ps: I referred to this link for creating the Custom ListView with Images and Text.