代码之家  ›  专栏  ›  技术社区  ›  Aashish Kumar

getDrawable(int)在这行中是不推荐使用的警告:Drawable res=getContext()。getResources()。可提取(项目img_resId);

  •  -3
  • Aashish Kumar  · 技术社区  · 7 年前

    我已经创建了自己的自定义适配器。在这段代码中,我得到getDrawable(int)是不推荐的警告,在这一行: Drawable res = getContext().getResources().getDrawable(item.img_resId); .

    Android getResources().getDrawable() deprecated API 22

    Android: Alternative for context.getDrawable()

    但在我的情况下,他们都没有工作。

    我的代码:

    public class CustomAdapter extends ArrayAdapter<ItemDataObject> {
    private static class ViewHolder {
        ImageView img;
        TextView title;
        TextView sub_title;
    }
    
    public CustomAdapter(Context context, ArrayList<ItemDataObject> list_item_details) {
        super(context, 0, list_item_details);
    }
    
    @NonNull
    @Override
    public View getView(int position, View convertView, @NonNull ViewGroup parent) {
        // Get the data item for this position
        ItemDataObject item = getItem(position);
        // Check if an existing view is being reused, otherwise inflate the view
        ViewHolder viewHolder; // view lookup cache stored in tag
        if (convertView == null) {
            // If there's no view to re-use, inflate a brand new view for row
            viewHolder = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(getContext());
            convertView = inflater.inflate(R.layout.listview_item, parent, false);
            viewHolder.img = convertView.findViewById(R.id.img);
            viewHolder.title = convertView.findViewById(R.id.tvTitle);
            viewHolder.sub_title = convertView.findViewById(R.id.tvSubTitle);
            // Cache the viewHolder object inside the fresh view
            convertView.setTag(viewHolder);
        } else {
            // View is being recycled, retrieve the viewHolder object from tag
            viewHolder = (ViewHolder) convertView.getTag();
        }
        // Populate the data from the data object via the viewHolder object into the template view.
        assert item != null;
        Drawable res = getContext().getResources().getDrawable(item.img_resId);
        viewHolder.img.setImageDrawable(res);
        viewHolder.title.setText(item.title);
        viewHolder.sub_title.setText(item.subtitle);
        // Return the completed view to render on screen
        return convertView;
        }
    }
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Ricardo    7 年前

    现在你应该使用

    Drawable drawable = ContextCompat.getDrawable(this,R.drawable.my_drawable);
    

    哪里 this 你通过了吗 context 如果您使用的是小部件,只需 如果您是从活动中打来的,或 getActivity() 如果您是从Fragment调用

    Context

    Context context;
    public CustomAdapter(Context context, ArrayList<ItemDataObject> list_item_details) {
        super(context, 0, list_item_details);
        this.context = context;
    }
    

    现在您可以拨打:

    Drawable drawable = ContextCompat.getDrawable(context,R.drawable.my_drawable);