如何在 Adapter.java 上使用 getResources()

How to use getResources() on a Adapter.java

我想在我的 TabView 上添加图标,但我卡住了,因为我无法在自定义 TabAdapter 中使用 getResources()。我已经尝试使用 getAplicationContext().getResources, getActivity.getResources(),但我仍然看到消息 "cannot resolve method"。有人可以帮助我吗?

   package com.glapps.mobile.codifynotes.Adapter;
   import android.content.Context;
   import android.graphics.drawable.Drawable;
   import android.support.v4.app.Fragment;
   import android.support.v4.app.FragmentManager;
   import android.support.v4.app.FragmentStatePagerAdapter;
   import android.text.Spannable;
   import android.text.SpannableString;
   import android.text.style.ImageSpan;
   import com.glapps.mobile.codifynotes.Activity.MainActivity;
   import com.glapps.mobile.codifynotes.Fragment.CodifyFragment;
   import com.glapps.mobile.codifynotes.Fragment.Configuracoes.ConfiguracoesFragment;

   import com.glapps.mobile.codifynotes.Fragment.DecodifyFragment;
   import com.glapps.mobile.codifynotes.R;
   public class TabAdapter extends FragmentStatePagerAdapter {

private String[] tituloAba = {"CODIFICAR", "DECODIFICAR", "CONFIGURAÇÕES"};
private int[] imageResId = {
        R.drawable.ic_action_lock_closed,
        R.drawable.ic_action_lock_closed,
        R.drawable.ic_action_settings_white
};
public TabAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int position) {
    Fragment fragment = null;

    switch (position){

        case 0:
            fragment = new CodifyFragment();
            break;
        case 1:
            fragment = new DecodifyFragment();
            break;
        case 2:
            fragment = new ConfiguracoesFragment();
    }


    return fragment;
}


@Override
public int getCount() {
    return tituloAba.length;
}

@Override
public CharSequence getPageTitle(int position) {
    return tituloAba[position];
    Drawable image = getResources().getDrawable(imageResId[position]);
    image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight());
    SpannableString sb = new SpannableString(" ");
    ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM);
    sb.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return sb;
}


   }

Error image

谢谢!

创建变量上下文

private Context context; 
//in the Constructor, pass the context in the parametres
public TabAdapter(FragmentManager fm, Context context) {
   super(fm);
   this.context = context;
}

您可以通过以下方式使用它:

context.getResources().

试试这个方法

Drawable image = getActivity().getResources().getDrawable(imageResId[position]);

Drawable image = getContext().getResources().getDrawable(imageResId[position]);