Дубликаты элементов, добавленные в Gridlayout с помощью пользовательского ButtonAdapter, расширяют базовый адаптер

#android #android-layout

#Android #android-layout

Вопрос:

Мне нужна помощь по этому вопросу. Когда я добавлял элементы в макет сетки, некоторые дубликаты элементов добавлялись в контейнер, и при прокрутке их позиции менялись. Вот XML и Java-код.

Макет:

   <RelativeLayout
     android:id="@ id/relativeLayout1" 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
      <TableRow android:layout_width="wrap_content" android:paddingTop="20dp" android:layout_height="wrap_content" android:id="@ id/tableRow2" android:layout_centerHorizontal="true" android:background="@color/transparent" android:minHeight="110dp">
          <ImageView android:layout_height="wrap_content" android:layout_width="wrap_content" android:src="@drawable/school_logo_default" android:layout_gravity="bottom" android:id="@ id/school_logo"></ImageView>
      </TableRow>

    <ImageView
      android:layout_width="fill_parent"
      android:layout_height="90dip"
      android:layout_alignParentTop="true"
      android:src="@drawable/gradient_top"
      android:scaleType="fitXY"
    />
    <ImageView
      android:layout_width="fill_parent"
      android:layout_height="90dip"
      android:layout_alignParentBottom="true"
      android:src="@drawable/gradient_bottom"
      android:scaleType="fitXY"

    />
     <LinearLayout
      android:id="@ id/top"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content" android:gravity="left|top">
         <TextView android:layout_height="wrap_content" android:textColor="@color/white" android:layout_weight="1" android:textStyle="bold" android:text="@string/userName" android:layout_width="wrap_content" android:layout_gravity="center_vertical" android:layout_marginRight="20dip" android:gravity="left|top" android:background="@color/transparent" android:paddingLeft="5dp" android:textSize="16px" android:paddingTop="5dp" android:id="@ id/username"></TextView>
    </LinearLayout>

    <LinearLayout
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:layout_weight="1"
      android:paddingBottom="20dip"
      android:layout_alignParentBottom="true"
      android:id="@ id/bottom">
        <ImageView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@ id/screen_icon" android:src="@drawable/sl_tools"></ImageView>

    </LinearLayout>

     <TableRow android:layout_width="wrap_content" android:gravity="center" android:layout_height="wrap_content" android:id="@ id/tableRow1" android:layout_centerInParent="true" android:background="@color/transparent">
        <ListView android:columnWidth="120dp" android:id="@ id/gridView1" android:numColumns="4" android:verticalSpacing="10dip" android:gravity="center"  android:horizontalSpacing="10dip" android:scrollbars="vertical" android:layout_gravity="center" android:stretchMode="columnWidth" android:background="@color/transparent" android:paddingTop="140dip" android:paddingBottom="80dip"></ListView>
    </TableRow>

   </RelativeLayout>

</FrameLayout>
  

Класс MyInternet:

 package com.explore.home;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.AndroidException;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.explore.objects.PInfoItem;
import com.explore.utils.DMS;
import com.explore.utils.Utils;



public class MyInternet extends Activity {

    private static final String LOG = "My Internet";

    public List<AppInfo> listApps = new ArrayList<AppInfo>();

    LayoutInflater inflator;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);

        super.onCreate(savedInstanceState);
        inflator = getLayoutInflater();

        setContentView(R.layout.myinternet);

        TextView tv = (TextView) findViewById(R.id.username);
        tv.setText(DMS.userProfile.user_fname   " "   DMS.userProfile.user_lname);

        FrameLayout lLayout = (FrameLayout) findViewById(R.id.myinternetlayout);
        lLayout.setBackgroundColor(Color.parseColor(DMS.deviceSettings.Background_Color));

        try
        {
           listApps = Utils.getAppsForScreen(getBaseContext(), "myinternet");
        }
        catch (IOException e) 
        {
             Toast.makeText(getBaseContext(), "Error MyInternet - "  e.getMessage(), Toast.LENGTH_SHORT).show();
        }

        ImageView iv1 = (ImageView)findViewById(R.id.school_logo);
        iv1.setImageBitmap(Utils.getBitmapByURL(DMS.deviceConfig.curriculum_loft_url   DMS.deviceSettings.School_Logo));    

        GridView gv = (GridView)findViewById(R.id.gridView1);
        gv.setAdapter(new ButtonAdapter(this));
    }



    class MyOnClickListener implements OnClickListener {
         private final int position;

         public MyOnClickListener(int position)  {
          this.position = position;
         }

         public void onClick(View v) {

             Log.i(LOG, "handler="   listApps.get(position).appName);
             try {
                handler(listApps.get(position));
            } catch (AndroidException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

         }
        }

    private void handler(AppInfo appInfo) throws AndroidException, ClassNotFoundException 
    {

        if(appInfo.type==0) // Shell Out APK
        {

            File realFilePath = new File("/data/data/com.explore.home/files/"  appInfo.appFileName);
            PackageManager pm = getBaseContext().getPackageManager();
            PackageInfo packageInfo = pm.getPackageArchiveInfo( realFilePath.getAbsolutePath(),0);

            //PackageManager pm = getPackageManager();
            //Intent il = pm.getLaunchIntentForPackage(appInfo.packageName); 
            Intent il = pm.getLaunchIntentForPackage(packageInfo.packageName); 
            //Intent i = new Intent();
            il.setAction(Intent.ACTION_MAIN);
            il.addCategory(Intent.CATEGORY_LAUNCHER);

            il.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            ComponentName cn = new ComponentName(packageInfo.packageName, il.getComponent().getClassName());
            il.setComponent(cn);
            startActivity(il);

            return;
        }
        if(appInfo.type==1) // Shell Out Hyper Link
        {
            Uri uriUrl = Uri.parse(appInfo.url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uriUrl);  
            startActivity(intent);
            }

        else {
            Toast.makeText(this, "Not Yet Implemented", Toast.LENGTH_LONG).show();
        }

    }


    class ButtonAdapter extends BaseAdapter {
         private Context mContext;

         // Gets the context so it can be used later
         public ButtonAdapter(Context c) {
          mContext = c;
         }

         // Total number of things contained within the adapter
         public int getCount() {
              return listApps.size();
         }

          // Require for structure, not really used in my code.
         public Object getItem(int position) {
          return null;
         }

         // Require for structure, not really used in my code. Can
         // be used to get the id of an item in the adapter for
         // manual control.
         public long getItemId(int position) {
          return position;
         }

         public View getView(int position, View convertView, ViewGroup parent) {
             TableLayout ll;
          if (convertView == null) {
                 Log.i(LOG, "position="   position);
                 Log.i(LOG, "count="   listApps.size());
                 for(int i=0; i<listApps.size(); i  ) {
                     Log.i(LOG, "apps="   listApps.get(i).appName);
                 }
                 // if it's not recycled, initialize some attributes
                 AppInfo appInfo = listApps.get(position);
                 Log.i(LOG, "app name ="   appInfo.appName);
                 ll = (TableLayout)inflator.inflate(R.layout.app, null, true);

                 ImageView iv1 = (ImageView)ll.findViewById(R.id.app_icon);
                 TextView iv2 = (TextView)ll.findViewById(R.id.app_title);
                 iv2.setText(appInfo.appName);

                 if(appInfo.type==0)
                 {
                    iv1.setImageBitmap(Utils.getAPKIcon(getApplicationContext(), appInfo));

                 }else
                 {
                     if(appInfo.icon!=null)
                     {
                         iv1.setImageBitmap(appInfo.icon);
                     }
                 }

                 iv1.setOnClickListener(new MyOnClickListener(position));
                 iv2.setOnClickListener(new MyOnClickListener(position));


           }
          else {
             ll = (TableLayout) convertView;
          }

          return ll;
         }
        }

}
  

Пожалуйста, дайте мне знать, почему некоторые повторяющиеся элементы добавлены вместо реальных элементов. При прокрутке их позиции изменились.

Ответ №1:

удалите условие и готово

  if (convertView == null)