2016-07-17 3 views
0

В моем приложении у меня есть меню прокрутки, и я использую эту функцию для полных пунктов меню. Но большую часть времени я получаю ошибку памяти. Я не ошибаюсь в эмуляторе. Но мое устройство терпит неудачу. Я попыталсяНагрузочные ролики эффективно не используют большую память

android:hardwareAccelerated="false" 
    android:largeHeap="true" 

и уменьшение изображения размер тоже. Но устройство говорит, что он занимает слишком много памяти. Я хочу, чтобы мое приложение быстрее загружалось и работала с памятью. Я все еще стартер в андроиде. Я видел несколько статей об эффективном загрузке изображений. Но я не понял. Может ли кто-нибудь помочь мне с некоторым примером кода?

public void RefreshMenuItems(int category) { 
    //Create menu scroller 
    LinearLayout.LayoutParams card_lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT); 
    card_lp.setMargins(dp(5), 0, dp(5), 0); 

    LinearLayout.LayoutParams image_lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 0); 
    image_lp.setMargins(dp(40), dp(5), dp(40), dp(5)); 
    image_lp.weight = 0.5f; 

    LinearLayout.LayoutParams desc_lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0); 
    desc_lp.weight = 0.32f; 

    LinearLayout.LayoutParams title_lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0); 
    title_lp.weight = 0.08f; 

    RelativeLayout.LayoutParams price_rp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
    price_rp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); 

    RelativeLayout.LayoutParams buy_rp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
    buy_rp.addRule(RelativeLayout.ALIGN_PARENT_LEFT); 

    LinearLayout.LayoutParams bottom_lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0); 
    bottom_lp.weight = 0.1f; 

    //fill menu 
    for (int i = 0; i < item_title.length; i++) { 
     final int currenti = i; 

     if ((item_category[i] == category) || category == 0) { 
      TextView title = new TextView(this); 
      title.setText(item_title[currenti]); 
      title.setGravity(Gravity.CENTER); 
      title.setTextColor(0xff212121); 
      title.setPadding(dp(10), dp(0), dp(10), dp(0)); 
      title.setTypeface(null, Typeface.BOLD); 
      title.setLayoutParams(title_lp); 
      title.setBackgroundResource(R.drawable.borderradius2); 
      title.setTextSize(fontpercent_screenheight(2.5)); 

      ImageView item = new ImageView(this); 
      item.setImageResource(getResources().getIdentifier(item_image[i], "drawable", getPackageName())); 
      item.setScaleType(ScaleType.FIT_CENTER); 
      item.setAdjustViewBounds(true); 
      item.setLayoutParams(image_lp); 

      TextView desc = new TextView(this); 
      desc.setText(item_shortdesc[currenti]); 
      desc.setPadding(dp(10), dp(5), dp(10), dp(5)); 
      desc.setLayoutParams(desc_lp); 
      desc.setTextSize(fontpercent_screenheight(2.5)); 

      TextView price = new TextView(this); 
      price.setText(String.format(sign + "%.2f", Double.parseDouble(item_price[currenti]))); 
      price.setPadding(0, dp(5), dp(10), dp(5)); 
      price.setLayoutParams(price_rp); 
      price.setTextSize(fontpercent_screenheight(2.5)); 

      buy = new TextView(this); 
      buy.setText(R.string.MenuAddToOrderButton); 
      buy.setPadding(dp(10), dp(5), 0, dp(5)); 
      buy.setTextColor(0xffff0000); 
      buy.setLayoutParams(buy_rp); 
      buy.setTextSize(fontpercent_screenheight(2.5)); 
      buy.setClickable(true); 
      buy.setOnClickListener(new OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        addItemToOrder(currenti); 
       } 
      }); 
      buy.setOnTouchListener(new OnTouchListener() { 
       @Override 
       public boolean onTouch(View v, MotionEvent event) { 
        if (event.getAction() == MotionEvent.ACTION_DOWN) { 
         ((TextView) v).setTextColor(0xff212121); 
        } else if (event.getAction() == MotionEvent.ACTION_UP) { 
         ((TextView) v).setTextColor(0xffff0000); 
        } 
        return false; 
       } 
      }); 

      RelativeLayout bottom = new RelativeLayout(this); 
      bottom.setLayoutParams(bottom_lp); 
      bottom.addView(buy); 
      bottom.addView(price); 

      LinearLayout card = new LinearLayout(this); 
      card.setOrientation(LinearLayout.VERTICAL); 
      card.setLayoutParams(card_lp); 
      card.setBackgroundResource(R.drawable.borderradius1); 
      card.setWeightSum(1f); 
      card.setOnClickListener(new OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        Intent intent = new Intent(context, ItemProfile.class).putExtra("item_image", getResources().getIdentifier(item_image[currenti], "drawable", getPackageName())).putExtra("item_title", item_title[currenti]).putExtra("item_desc", item_desc[currenti]).putExtra("item_price", Double.parseDouble(item_price[currenti])); 
        startActivity(intent); 
       } 
      }); 

      card.addView(title); 
      card.addView(item); 
      card.addView(desc); 
      card.addView(bottom); 

      menu.addView(card); 
     } 
    } 
} 
+0

См. Мой ответ ниже. –

ответ

0

Каждый раз, когда я начинаю видеть цикл, который создает представления вручную, меня обычно беспокоят, что все происходит не оптимальным образом. Посмотрите еще на https://developer.android.com/guide/topics/ui/declaring-layout.html. Вы можете захотеть просмотреть ListView, похоже, что вы пытаетесь построить его вручную.

+0

Я не понимаю. –

+0

Похоже, вы пытаетесь создать меню, содержащее список элементов меню. Список не должен создаваться в андроиде, создавая сами виды. Вы должны использовать ListView и адаптер. –

+0

, но как я могу изменить это на адаптер? –

Смежные вопросы