Android: setImageResource with LayoutInflater
-
26-10-2019 - |
문제
I have a listView, a main xml file and a customListview xml file. for my listView I am using a custom ArrayAdapter which I made.
Now, i would like to set an image as a resource in my MainActivity class. the problem is that the image is in another xml, not in this which i set the contentView.
I am trying this code but nothing happens:
LayoutInflater mInflater=(LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
View view=mInflater.inflate(R.layout.custom_row_view,null);
ImageView statusOk=(ImageView)view.findViewById(R.id.statusOkImage);
statusOk.setImageResource(R.drawable.ic_launcher);
If interested in all the code, youcan see here: ImageView setVisibility(0) and null pointer exception
해결책
Change your get method in base adapter:
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.custom_row_view, null);
holder = new ViewHolder();
holder.txtName = (TextView) convertView.findViewById(R.id.name);
holder.txtCityState = (TextView) convertView.findViewById(R.id.cityState);
holder.txtPhone = (TextView) convertView.findViewById(R.id.phone);
holder.statusOk=(ImageView)convertView.findViewById(R.id.imageView1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
statusOk.setVisibility(View.VISIBLE);
holder.txtName.setText(searchArrayList.get(position).getName());
holder.txtCityState.setText(searchArrayList.get(position).getCityState());
holder.txtPhone.setText(searchArrayList.get(position).getPhone());
return convertView;
}
static class ViewHolder {
TextView txtName;
TextView txtCityState;
TextView txtPhone;
ImageView statusOk;
}
제휴하지 않습니다 StackOverflow