用于NavDrawer的imageview中的图像配置文件

时间:2015-07-18 13:10:29

标签: android parse-platform imageview

我从Parse获取图像文件,基本上是用户的个人资料图片。 但是现在我无法在NavDrawer中显示它,因为它不是一个imageview而我得到的是一个Image,

这是我的Mainactivity.xml

   public class MainActivity extends AppCompatActivity {

    private Toolbar mToolbar;
    private RecyclerView mRecyclerView;
    private RecyclerView.LayoutManager mLayoutManager;
    private DrawerLayout Drawer;
    private RecyclerView.Adapter mAdapter;
    private ActionBarDrawerToggle mDrawerToggle;
    private List<DrawerItem> navigationItemsList;



    public String HEADER_NAME;// = "bharath";
    public String HEADER_EMAIL = "bharath@someemail.com";
    public int HEADER_IMAGE ;//= R.drawable.bharath;

    private final static int ATTENDANTS_LIST_FRAGMENT = 1;
    private final static int EVENTS_LIST_FRAGMENT = 2;
    private final static int ADD_ATTENDANT_FRAGMENT = 3;
    private final static int ADD_EVENTS_FRAGMENT = 4;
    private final static int MY_DONATIONS = 5;
    private final static int SETTINGS_FRAGMENT = 6;


    private int currentFragment = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mToolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(mToolbar);

        navigationItemsList = new ArrayList<DrawerItem>();
        addItemsToNavigationList();


        mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView);
        mRecyclerView.setHasFixedSize(true);


        ParseUser userName = ParseUser.getCurrentUser();
        HEADER_NAME = userName.getUsername();
        HEADER_EMAIL = userName.getEmail();
        mAdapter = new com.charity.dogood.dogood.adapters.NavDrawerAdapter(navigationItemsList, this, HEADER_NAME, HEADER_EMAIL, HEADER_IMAGE);
        mRecyclerView.setAdapter(mAdapter);


        //Parse Image and details of the logged in user
        // Locate the class table named "ImageUpload" in Parse.com
        ParseQuery<ParseObject> query = new ParseQuery("User");
        Log.d("Mainactivity", "After query 1");

        ParseUser currentUser = ParseUser.getCurrentUser();

        Log.d("Mainactivity", "After query 2");
        query.whereEqualTo("username", "bro");
        Log.d("Mainactivity", "After query 3");
        Log.d("Mainactivity", currentUser.getUsername());
        // String usernam = (String)currentUser;

        if (currentUser != null) {
            Log.d("Mainactivity", "came to current user check statement");

            currentUser.fetchIfNeededInBackground(new GetCallback<ParseObject>() {
           // query.getInBackground("bro", new GetCallback<ParseObject>() {

                @Override
                public void done(ParseObject object, ParseException e) {


                    if (e == null) {
                        ParseFile fileObject = (ParseFile) object.getParseFile("ImageProfile");


                        fileObject.getDataInBackground(new GetDataCallback() {

                            @Override
                            public void done(byte[] bytes, ParseException e) {
                                if (e == null) {
                                    Toast.makeText(MainActivity.this, "we got data!", Toast.LENGTH_LONG).show();
                                    Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                                    HEADER_IMAGE =  (ImageView)findViewById(R.id.c)

                                    // HEADER_IMAGE image = (ImageView) fin
                                } else {
                                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                                    builder.setMessage(e.getMessage());
                                    builder.setTitle("Sorry");
                                    builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            dialogInterface.dismiss();
                                        }
                                    });
                                    AlertDialog dialog = builder.create();
                                    dialog.show();
                                }

                            }
                        });
                    } else {
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        builder.setMessage(e.getMessage());
                        builder.setTitle("Sorry");
                        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                            }
                        });
                        AlertDialog dialog = builder.create();
                        dialog.show();

                    }

                }
            });
            Log.d("Mainactivity", "After query 4");

        }

        final GestureDetector mGestureDetector =   new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener()


                {
                 @Override
                 public boolean onSingleTapUp(MotionEvent e) {return true;}
                });



        mRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
            @Override
            public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
                View child = recyclerView.findChildViewUnder(motionEvent.getX(),motionEvent.getY());

                if (child != null && mGestureDetector.onTouchEvent(motionEvent)){
                    Drawer.closeDrawers();
                    onTouchDrawer(recyclerView.getChildLayoutPosition(child));
                   // onTouchDrawer(recyclerView.getChildLayoutPosition(child));
                    return true;
                }
                return false;
            }



            @Override
            public void onTouchEvent(RecyclerView rv, MotionEvent e) {

            }

            @Override
            public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

            }
        });
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        Drawer = (DrawerLayout) findViewById(R.id.DrawerLayout);
        mDrawerToggle = new ActionBarDrawerToggle(this, Drawer, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
            }
        };

        Drawer.setDrawerListener(mDrawerToggle);
        mDrawerToggle.syncState();

        onTouchDrawer(1); }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.

        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.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    private void openFragments(final Fragment fragment)
    {
        getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_left).   replace(R.id.container, fragment).commit();
    }



    private void onTouchDrawer(final int position)
    {
        currentFragment = position;
        switch (position)
        {
            case ATTENDANTS_LIST_FRAGMENT:
                openFragments(new AttendanceListFragment());
                setTitle(getString(R.string.all_charities));
                break;

            case ADD_ATTENDANT_FRAGMENT:
                openFragments(new AddAttendantFragment());
                setTitle(getString(R.string.view_causes));
                break;

            case EVENTS_LIST_FRAGMENT:
                openFragments(new EventsListFragment());
                setTitle(getString(R.string.add_charity));
                break;

            case ADD_EVENTS_FRAGMENT:
                openFragments(new AddEventFragment());
                setTitle(getString(R.string.make_donation));
                break;


            case MY_DONATIONS:
                openFragments(new AddEventFragment());
                setTitle(getString(R.string.my_dontations));
                break;



            case SETTINGS_FRAGMENT:
                startActivity(new Intent(this, PreferenceActivity.class));
                //ToDO

                default:
                    return;


        }
    }


    private void setTitle(String title)
    {
        getSupportActionBar().setTitle(title);
    }

    private void addItemsToNavigationList(){
        navigationItemsList.add(new DrawerItem(getString(R.string.all_charities), R.drawable.ic_action_attendant_list));
        navigationItemsList.add(new DrawerItem(getString(R.string.add_charity), R.drawable.ic_action_events_list));
        navigationItemsList.add(new DrawerItem(getString(R.string.view_causes), R.drawable.ic_action_add_attendant));
        navigationItemsList.add(new DrawerItem(getString(R.string.make_donation), R.drawable.ic_action_add_event));
        navigationItemsList.add(new DrawerItem(getString(R.string.my_dontations), R.drawable.ic_action_add_attendant));
        navigationItemsList.add(new DrawerItem(getString(R.string.settings), R.drawable.ic_action_settings));
    }

我的NavDrawerAdapter

package com.charity.dogood.dogood.adapters;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.charity.dogood.dogood.R;
import com.charity.dogood.dogood.models.DrawerItem;

import java.util.List;

/**
 * Created by Valentine on 6/18/2015.
 */
public class NavDrawerAdapter extends RecyclerView.Adapter<NavDrawerAdapter.ViewHolder> {

    //Declare variable to identify which view that is being inflated
    //The options are either the Navigation Drawer HeaderView or the list items in the Navigation drawer
    private static final int TYPE_HEADER = 0;
    private static final int TYPE_ITEM = 1;

    // String Array to store the passed titles Value from MainActivity.java
    private String mNavTitles[];

    // Int Array to store the passed icons resource value from MainActivity.java
    private int mIcons[];

    //String Resource for header View Name
    private String name;

    //int Resource for header view profile picture
    private int profile;

    //String for the email displayed in the Navigation header
    private String email;

    private Context mContext;

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_ITEM) {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.nav_drawer_row,parent,false); //Inflating the layout

            ViewHolder vhItem = new ViewHolder(v,viewType); //Creating ViewHolder and passing the object of type view

            return vhItem; // Returning the created object

            //inflate your layout and pass it to view holder

        } else if (viewType == TYPE_HEADER) {

            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.header,parent,false); //Inflating the layout

            ViewHolder vhHeader = new ViewHolder(v,viewType); //Creating ViewHolder and passing the object of type view

            return vhHeader; //returning the object created


        }
        return null;

    }

    //Next we override a method which is called when the item in a row is needed to be displayed, here the int position
    // Tells us item at which position is being constructed to be displayed and the holder id of the holder object tell us
    // which view type is being created 1 for item row
    @Override
    public void onBindViewHolder(NavDrawerAdapter.ViewHolder holder, int position) {
        if(holder.Holderid ==1) {                              // as the list view is going to be called after the header view so we decrement the
            // position by 1 and pass it to the holder while setting the text and image
            holder.textView.setText(mNavTitles[position - 1]); // Setting the Text with the array of our Titles
            holder.imageView.setImageResource(mIcons[position -1]);// Settimg the image with array of our icons
        }
        else{

            holder.profile.setImageResource(profile);           // Similarly we set the resources for header view
            holder.Name.setText(name);
            holder.email.setText(email);
        }

    }


    @Override
    public int getItemCount() {
        return mNavTitles.length + 1;
    }


    public static class ViewHolder extends RecyclerView.ViewHolder{
        int Holderid;

        TextView textView;
        ImageView imageView;
        ImageView profile;
        TextView Name;
        TextView email;

        public ViewHolder(View itemView,int ViewType) {                 // Creating ViewHolder Constructor with View and viewType As a parameter
            super(itemView);


            // Here we set the appropriate view in accordance with the the view type as passed when the holder object is created

            if(ViewType == TYPE_ITEM) {
                textView = (TextView) itemView.findViewById(R.id.rowText); // Creating TextView object with the id of textView from nav_bar_rowrow.xml
                imageView = (ImageView) itemView.findViewById(R.id.rowIcon);// Creating ImageView object with the id of ImageView from nav_bar_row.xmlxml
                Holderid = 1;                                               // setting holder id as 1 as the object being populated are of type item row
            }
            else{


                Name = (TextView) itemView.findViewById(R.id.name);         // Creating Text View object from header.xml for name
                email = (TextView) itemView.findViewById(R.id.email);       // Creating Text View object from header.xml for email
                profile = (ImageView) itemView.findViewById(R.id.circleView);// Creating Image view object from header.xml for profile pic
                Holderid = 0;                                                // Setting holder id = 0 as the object being populated are of type header view
            }
        }

    }

    /**
     * With this method we determine what type of view being passed.
     * @param position
     * @return
     */
    @Override
    public int getItemViewType(int position) {
        if (isPositionHeader(position))
            return TYPE_HEADER;

        return TYPE_ITEM;
    }

    private boolean isPositionHeader(int position) {
        return position == 0;
    }

    public NavDrawerAdapter(List<DrawerItem> dataList, Context context, String Name, String Email, int Profile){ // MyAdapter Constructor with titles and icons parameter
        // titles, icons, name, email, profile pic are passed from the main activity as we


        mNavTitles = new String[dataList.size()];
        mIcons = new int[dataList.size()];

        for (int i = 0; i < dataList.size(); i++){
            mNavTitles[i] = dataList.get(i).getItemName();
            mIcons[i] = dataList.get(i).getImgResId();
        }
        mContext = context;
        name = Name;
        email = Email;
        profile = Profile;                     //here we assign those passed values to the values we declared here
        //in adapter
    }

}

我能够在抽屉中获取用户名和电子邮件,但是我应该如何处理bmp,我下载的位图将其显示在应用程序导航抽屉中?像这样的形象,

enter image description here

3 个答案:

答案 0 :(得分:0)

如果您从 Parse 获得[comment encoding = UTF-8 /] [module generate('http://www.eclipse.org/emf/compare')] [template public generateElement(comparison : Comparison)] [comment @main/] [file ('update.sql', false, 'UTF-8')] /*SQL UPDATE SCRIPT TEST*/ [comparison.getDifferences().toString() /] [/file] [/template] ,则只需将您的网址放入图片加载器库中。

以下库用于按URL加载图像:

1. Picasso

2. AQuery

3. Glide

编辑:

圆形ImageView的毕加索示例:

您必须创建以下java文件( CircleTransform.java ):

URL

你只需要打电话:

import com.squareup.picasso.Transformation;

public class CircleTransform implements Transformation {
    @Override
    public Bitmap transform(Bitmap source) {
        int size = Math.min(source.getWidth(), source.getHeight());

        int x = (source.getWidth() - size) / 2;
        int y = (source.getHeight() - size) / 2;

        Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
        if (squaredBitmap != source) {
            source.recycle();
        }

        Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());

        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        BitmapShader shader = new BitmapShader(squaredBitmap,
                BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
        paint.setShader(shader);
        paint.setAntiAlias(true);

        float r = size / 2f;
        canvas.drawCircle(r, r, r, paint);

        squaredBitmap.recycle();
        return bitmap;
    }

    @Override
    public String key() {
        return "circle";
    }
}

如果您需要进一步的帮助,请随时给我打电话。

快乐装载:)

答案 1 :(得分:0)

如果你在这里Bitmap

 Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

现在很简单,只需:

 yourImageView.setImageBitmap(bmp);

答案 2 :(得分:0)

在NavDrawerAdapter.java中 定义字段

Bitmap bitmapAvatar = null;

然后在函数onBindViewHolder(NavDrawerAdapter.ViewHolder holder,int position) 取代

holder.profile.setImageResource(profile);

if (bitmapAvatar != null) {
    holder.profile.setImageBitmap(bitmapAvatar);
} else {
    holder.profile.setImageResource(profile);
}

并创建一个函数(在外部类中)

public void setAvatar(Bitmap bmp) {
    this.bitmapAvatar = bmp;
    notifyDataSetChanged();
}

callig notifyDatasetChanged()将使用适配器实例更新包含当前数据的视图。

在MainActivity.java中 使用

private NavDrawerAdapter mAdapter;

而不是

private RecyclerView.Adapter mAdapter;

并且在GetDataCallback中,在Bitmap准备好与bmp变量一起使用后,删除该行

HEADER_IMAGE =  (ImageView)findViewById(R.id.c)

不需要在MainActivity中初始化ImageView,也不要使用分号。 删除后,在创建bmp后将以下调用代码放在同一位置:

mAdapter.setAvatar(bmp);

它将调用我们在适配器类中创建的函数并动态更改图像。