回收查看未显示的行图像

时间:2017-06-16 07:44:45

标签: android xml android-layout android-linearlayout android-relativelayout

我正在使用自定义适配器构建一个简单的回收视图,我已经设置了所有元素的位置,但不知何故,我的行的图像主要没有出现,我不知道为什么。

在我改变它出现的xml之前,基本上我有我的主要活动:

    public class PlantFeed extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener,PlantFeedAdapter.OnItemClickListener {

    //initialize fields

    String token;

    ArrayList<PlantPhotoUser> photos = new ArrayList<>();

    VolleyService mVolleyService;
    IResult mResultCallback = null;
    final String GETREQUEST = "GETCALL";

    String connectionTxt;

    String URL;

    String date;
    String lat;
    String lon;
    String alt;

    PlantFeedAdapter plantFeedAdapter;
    RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_plant_feed);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        connectionString connection = ((connectionString) getApplicationContext());
        connectionTxt = connection.getGlobalVarValue();

        URL = connectionTxt + "/fotos";


        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(PlantFeed.this,CameraCapture.class);
                startActivity(i);
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        recyclerView = (RecyclerView)findViewById(R.id.recycleView2);
        recyclerView.setHasFixedSize(true);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        plantFeedAdapter = new PlantFeedAdapter(getApplicationContext(), photos,PlantFeed.this);
        recyclerView.setAdapter(plantFeedAdapter);

        token = checkForToken();

        initVolleyCallback();

        mVolleyService = new VolleyService(mResultCallback,this);

        mVolleyService.getDataVolley(GETREQUEST,URL,token);

    }

    void initVolleyCallback(){
        mResultCallback = new IResult() {
            @Override
            public void notifySuccess(String requestType,JSONObject response) {
                Log.d("HELLL","hi1");
            }

            @Override
            public void notifySuccess(String requestType, JSONArray response) {
                PlantPhotoUser plantPhotoUser;
                Log.d("HELLLL","hi");
                for (int i=0; i < response.length(); i++) {
                    try {
                        JSONObject object = response.getJSONObject(i);
                        Log.d("objeto",object.toString());

                        int userId = object.getInt("userId");
                        Log.d("objeto",String.valueOf(userId));
                        String username = object.getJSONObject("user").getString("username");
                        Log.d("objeto",String.valueOf(username));
                        int plantId = object.getInt("plantId");
                        Log.d("objeto",String.valueOf(plantId));
                        String specie = object.getJSONObject("plant").getString("specie");
                        Log.d("objeto",String.valueOf(specie));

                        String path = object.getString("image");
                        Log.d("objeto",String.valueOf(path));
                        int fotoId = object.getInt("id");

                        if(object.getString("date") != null){
                            date = object.getString("date");
                        }

                        if(object.getString("lat") != null){
                            lat = object.getString("lat");
                        }

                        if(object.getString("lon") != null){
                            lon = object.getString("lon");
                        }

                        if(object.getString("altitude") != null){
                            alt = object.getString("altitude");
                        }

                        plantPhotoUser = new PlantPhotoUser(fotoId,plantId,userId,path,specie,date,lat,lon,alt,username);
                        photos.add(plantPhotoUser);


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                plantFeedAdapter.notifyDataSetChanged();

            }

            @Override
            public void notifyError(String requestType,VolleyError error) {
                Log.d("FAIL",error.toString());
            }
        };
    }

    public String checkForToken() {
        SharedPreferences sharedPref = getSharedPreferences("user", MODE_PRIVATE);
        String tokenKey = getResources().getString(R.string.token);
        String token = sharedPref.getString(getString(R.string.token), tokenKey); // take the token
        return token;
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.plant_feed, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.Perfil) {
            return true;
        }



        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            Intent i = new Intent(PlantFeed.this,CameraCapture.class);
            startActivity(i);
        } else if (id == R.id.nav_gallery) {
            Intent i = new Intent(PlantFeed.this,PlantFeed.class);
            startActivity(i);
        } else if (id == R.id.nav_slideshow) {
            Intent i = new Intent(PlantFeed.this,FamilyLibrary.class);
            startActivity(i);
        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onRowClick(int position, String name, int id, View view) {

    }

    @Override
    public void onTitleClicked(int position, int id, View clickedview) {
        Intent i = new Intent(this,PhotosForPlant.class);
        i.putExtra("plantId",String.valueOf(id));
        startActivity(i);
    }

    @Override
    public void onImageClicked(int position, int id, View clickedview) {
        Intent i = new Intent(this,PhotosForPlant.class);
        i.putExtra("plantId",String.valueOf(id));
        startActivity(i);
    }

    @Override
    public void onReportClicked(int position, int id, String name, View clickedview) {
        Log.d("HELLLO","HELLOO");
        showDialogReport(id,name);
    }



    @Override
    public void onUserIconClicked(int position, int id, View clickedview) {
        Intent i = new Intent(this,UserProfile.class);
        i.putExtra("userId",id);
        startActivity(i);
    }

    @Override
    public void onUsernameClicked(int position, int id, View clickedview) {
        Intent i = new Intent(this,UserProfile.class);
        i.putExtra("userId",id);
        startActivity(i);
    }

    @Override
    public void onAvaliationClicked(int position, int id, String name, View clickedview) {

    }


    private void showDialogReport(int id, String name) {
        Log.d("HELLLO","HELLOO");
        AlertDialog.Builder builder = new AlertDialog.Builder(PlantFeed.this);
        builder.setTitle(name);
        builder.setMessage("Tem a certeza que pretende reportar a fotografia?");
        builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                //TODO reportar base de dados
            }
        });
        builder.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.dismiss();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }
}

然后我有这样的客户适配器:

public class PlantFeedAdapter extends RecyclerView.Adapter<PlantFeedAdapter.ViewHolder> {

    private OnItemClickListener listener;

    public interface OnItemClickListener {
        void onRowClick(int position, String name, int id, View view);
        void onTitleClicked(int position, int id, View clickedview);
        void onImageClicked(int position,int id, View clickedview);
        void onReportClicked(int position, int id,String name, View clickedview);
        void onUserIconClicked(int position, int id, View clickedview);
        void onUsernameClicked(int position, int id, View clickedview);
        void onAvaliationClicked(int position, int id,String name, View clickedview);

    }

    private ArrayList<PlantPhotoUser> photos;
    private Context context;

    public PlantFeedAdapter(Context context, ArrayList<PlantPhotoUser> photos, OnItemClickListener listener) {
        this.photos = photos;
        this.context = context;
        this.listener = listener;
    }

    @Override
    public PlantFeedAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.plant_feed_row, viewGroup, false);
        return new ViewHolder(view);
    }


    @Override
    public void onBindViewHolder(final PlantFeedAdapter.ViewHolder viewHolder, final int i) {
        viewHolder.name.setText(photos.get(i).getSpecie());
        viewHolder.username.setText(photos.get(i).getUsernName());
        viewHolder.data.setText(photos.get(i).getDate().split("T")[0]);
        Log.d("data123",(photos.get(i).getDate().toString()));

        String urlFoto = "http://fe1b7efd.ngrok.io/" + photos.get(i).getPath();

        if(urlFoto.toLowerCase().contains("public/")){
            urlFoto = urlFoto.replace("public/","");
        }

        viewHolder.userIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (listener != null) {
                    listener.onUserIconClicked(viewHolder.getAdapterPosition(), photos.get(i).getUserId(), view);
                }
            }
        });

        viewHolder.username.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (listener != null) {
                    listener.onUsernameClicked(viewHolder.getAdapterPosition(),photos.get(i).getUserId(), view);
                }
            }
        });

        viewHolder.plantImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (listener != null) {
                    listener.onImageClicked(viewHolder.getAdapterPosition(), photos.get(i).getIdPlant(), view);
                }
            }
        });


        viewHolder.name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(listener != null){
                    listener.onTitleClicked(viewHolder.getAdapterPosition(),photos.get(i).getIdPlant(),v);
                }
            }
        });

        viewHolder.reportImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(listener != null){
                    listener.onReportClicked(viewHolder.getAdapterPosition(),photos.get(i).getIdPlant(),photos.get(i).getSpecie(),v);
                }
            }
        });

        /*viewHolder.avaliationFoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(listener != null){
                    listener.onAvaliationClicked(viewHolder.getAdapterPosition(),photos.get(i).getIdPlant(),photos.get(i).getSpecie(),v);
                }
            }
        });*/



        Picasso.with(context)
                .load(urlFoto)
                .resize(300, 300)
                .into(viewHolder.plantImg);
    }

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

    public class ViewHolder extends RecyclerView.ViewHolder{
        private TextView name;
        private ImageView userIcon;
        private TextView avaliationFoto;
        private ImageView plantImg;
        private ImageView foto;
        private TextView username;
        private ImageView reportImage;
        private TextView data;
        public ViewHolder(View view) {
            super(view);
            data = (TextView)view.findViewById(R.id.data);
            name = (TextView) view.findViewById(R.id.plantName);
            userIcon = (ImageView)view.findViewById(R.id.userIcon);
            plantImg = (ImageView)view.findViewById(R.id.plantPhoto);;
            username = (TextView)view.findViewById(R.id.password);
            reportImage = (ImageView)view.findViewById(R.id.cameraForbiden);

        }
    }


}

最后我的行xml,我觉得有问题

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#cfcfcf">
<LinearLayout
    android:layout_margin="10dp"
    android:background="#ffffff"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.android.volley.toolbox.NetworkImageView
        android:layout_weight="1"
        android:layout_width="120dp"
        android:layout_height="100dp"
        android:padding="0dp"
        app:srcCompat="@mipmap/ic_launcher"
        android:id="@+id/plantPhoto"
        android:background="#c7c7c7"
        />

    <LinearLayout
        android:layout_weight="20"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/plantName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="right"
                android:padding="15dp"
                android:text="TextView"
                android:textColor="#000"
                android:textSize="20dp" />

        <ImageView
            android:id="@+id/starIcon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="15dp"
            android:gravity="right"
            android:src="@drawable/ic_star" />

        </RelativeLayout>


        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:padding="15dp">


            <com.example.afcosta.inesctec.pt.android.Helpers.NexusBoldTextView
                android:id="@+id/data"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toStartOf="@+id/cameraForbiden"
                android:text="TextView"
                android:textColor="@color/base" />

            <ImageView
                android:id="@+id/cameraForbiden"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_alignParentEnd="true"
                android:src="@drawable/ic_no_photos" />

            <ImageView
                android:id="@+id/userIcon"
                android:layout_width="15dp"
                android:layout_height="15dp"
                android:gravity="left"
                android:layout_alignParentBottom="true"
                android:src="@drawable/ic_user" />

            <com.example.afcosta.inesctec.pt.android.Helpers.NexusBoldTextView
                android:id="@+id/password"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@+id/userIcon"
                android:text="Filipe"
                android:textColor="@color/base" />

        </RelativeLayout>

    </LinearLayout>
</LinearLayout>

问题在于这个元素:

<com.android.volley.toolbox.NetworkImageView
    android:layout_weight="1"
    android:layout_width="120dp"
    android:layout_height="100dp"
    android:padding="0dp"
    app:srcCompat="@mipmap/ic_launcher"
    android:id="@+id/plantPhoto"
    android:background="#c7c7c7"
    />

2 个答案:

答案 0 :(得分:0)

使用Picasso

添加centerCrop()
Picasso.with(context)
  .load(url)
  .resize(50, 50)
  .centerCrop()
  .into(imageView)

答案 1 :(得分:0)

在适配器和ViewHolder中更改此行,因为类型转换是错误的。 :

private ImageView plantImg;
plantImg = (ImageView)view.findViewById(R.id.plantPhoto);;

private NetworkImageView plantImg; plantImg= (NetworkImageView) findViewById(R.id .plantPhoto);然后设置图片。

修改

`private ImageLoader mImageLoader;
 mImageLoader = CustomVolleyRequestQueue.getInstance(this.getApplicationContext())
                .getImageLoader();
 mImageLoader.get(url, ImageLoader.getImageListener(mNetworkImageView,
                R.mipmap.truiton_short, android.R.drawable
                        .ic_dialog_alert));
        mNetworkImageView.setImageUrl(url, mImageLoader);`

使用此链接http://www.truiton.com/2015/03/android-volley-imageloader-networkimageview-example/作为进一步指南。