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

时间:2016-12-07 01:19:48

标签: android android-studio slidingmenu getresource

我想在我的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

谢谢!

2 个答案:

答案 0 :(得分:5)

创建变量上下文

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().

答案 1 :(得分:0)

试试这种方式

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

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