2016-04-16 6 views
2

をスクロールしたときにこれは私のアダプターのコードです:ラグrecyclerview

public class CatAdapter extends RecyclerView.Adapter<CatAdapter.ViewHolder> { 
ArrayList<CatModel> objects_; 
Context context; 
Class res = R.drawable.class; 

public class ViewHolder extends RecyclerView.ViewHolder { 
    TextView cat_text,cat_des; 
    ImageView cat_img; 

    public ViewHolder(View v) { 
     super(v); 
     cat_text = (TextView) v.findViewById(R.id.cat_txt); 
     cat_des = (TextView) v.findViewById(R.id.cat_des); 
     cat_img = (ImageView) v.findViewById(R.id.cat_img); 
    } 
} 

public CatAdapter(ArrayList<CatModel> arrayList, Context context) { 
    this.context = context; 
    objects_ = arrayList; 
} 

@Override 
public CatAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, 
               int viewType) { 
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cat_list_view, parent, false); 
    return new ViewHolder(v); 
} 

@Override 
public void onBindViewHolder(ViewHolder holder, int position) { 
    holder.cat_text.setText(objects_.get(position).txt); 
    holder.cat_des.setText(objects_.get(position).des); 
    try { 
     Field field = res.getField(objects_.get(position).img); 
     int drawableId = field.getInt(null); 
     holder.cat_img.setImageDrawable(context.getResources().getDrawable(drawableId)); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

@Override 
public int getItemCount() { 
    return objects_.size(); 
} 
} 

CatModelクラス

public class CatModel { 
    public String txt,img,des; 
} 

CatModel.imgは、私がR.stringsに入れて、私のdrawablesのIDです。 私のすべての項目int arraylistは約20項目です。私のdrawablesは、SVGに最適化されています。しかし、私がスクロールしているとき、それは滑らかではありません。それを最適化するために私は何ができますか?

+0

。それは遅くなることが知られており、リフレクションを回避するためにコードをリファクタリングします。 – Francesc

+0

もっと説明できますか? @Francesc –

+0

resオブジェクト(getField)で反射を使用しています。反射は本質的に遅く、おそらく16msの障壁の上にあなたを押しているでしょう。私はあなたが何をしようとしているのかはよく分かりませんが、あなたのドロウアブルのリストまたはハッシュマップを作成し、そのリストまたはハッシュマップを使ってドロウブルをその位置にリンクすることができるはずです。 – Francesc

答えて

1

リフレクションではなく、直接リソースを使用してドロウアブルにアクセスする必要があります。

それぞれの "drawables"フォルダ(drawable-xhdpi、drawable-xxhdpiなど)にドロアブルを配置する必要があります。描画可能にように

CatModel catModel = new CatModel(); 
catModel.drawable = R.drawable.my_drawable_1; 

のように、あなたのドロウアブルの一つであり、どこ

public class CatModel { 
    public String txt,des; 
    public int drawable; 
} 

:次に、あなたのオブジェクトには、各描画可能に関連付けられているint型を参照します。

は、その後、あなたのアダプタで、あなたはこのようにそれを使用する:あなたは、あなたのonBindViewHolderにリフレクションを使用している

@Override 
public void onBindViewHolder(ViewHolder holder, int position) { 
    holder.cat_text.setText(objects_.get(position).txt); 
    holder.cat_des.setText(objects_.get(position).des); 
    holder.img.setImageResource(objects_.get(position).drawable); 
} 
+0

なぜ私はそれを考えなかったのですか?私は値からdrawables intを得ることができますか? –

+0

はい、各drawableに関連付けられたint値は、Rクラスを通して使用してください。 – Francesc

+0

ありがとうございますが少し遅れました –