对话没有被解雇

时间:2016-10-01 10:39:46

标签: android dialog dismiss

我有recyclerviewonClick recyclerview项目的dialog我创建了一个Dialog

为每个项目创建

dialog,但问题是,当我点击dialog剂量时,不会被解雇。它再次显示我点击并创建dialog的项目数。

假设我现在点击了一个项目dialog被打开,如果我在外面点击它就会被关闭。现在是第二次,如果我点击另一个项目并在外面点击它再次显示public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ContactHolder> { private List<Contact> contactList; File myDir1; private Context mContext; private Boolean fileExists; private File file; public ContactAdapter(Context context, List<Contact> contactList) { this.contactList = contactList; this.mContext = context; } @Override public ContactHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_layout,null); ContactHolder mh = new ContactHolder(v); return mh; } @Override public void onBindViewHolder(final ContactHolder contactHolder, int i) { final Contact contact = contactList.get(i); // Log.e("Imagename",""+"http://xesoftwares.co.in/contactsapi/profile_images/85368a5bbd6cffba8a3aa202a80563a2.jpg");//+feedItem.getThumbnail()); Target target = new Target() { @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { // your code here ... contactHolder.thumbnail.setImageBitmap(bitmap); Log.e("ProfileImage",contact.getmProfileImage()); SaveImages(bitmap, contact.getmProfileImage()); } @Override public void onBitmapFailed(Drawable errorDrawable) { contactHolder.thumbnail.setImageDrawable(errorDrawable); // do error handling as required } @Override public void onPrepareLoad(Drawable placeHolderDrawable) { contactHolder.thumbnail.setImageDrawable(placeHolderDrawable); } }; contactHolder.thumbnail.setTag(target); String url = ServiceUrl.getBaseUrl() + ServiceUrl.getImageUserUrl() + contact.getmProfileImage(); Log.e("url",url); if(contact.getmProfileImage().equals("")) { file = new File(""); fileExists = file.exists(); contactHolder.thumbnail.setImageDrawable(ContextCompat.getDrawable(mContext,R.drawable.ic_account_circle_black_48dp)); } else { file = new File(Environment.getExternalStorageDirectory() + "/ContactProfileImages/" + contact.getmProfileImage()); fileExists = file.exists(); } if(fileExists) { Log.e("fileExists",file.getAbsolutePath()); BitmapFactory.Options bmOptions = new BitmapFactory.Options(); Bitmap bitmap = BitmapFactory.decodeFile(file.getPath(), bmOptions); contactHolder.thumbnail.setImageBitmap(bitmap); } else { Log.e("Picasso",file.getAbsolutePath()); Picasso.with(mContext).load(url) .error(R.drawable.ic_account_circle_black_24dp) .placeholder(R.drawable.ic_account_circle_black_24dp) .resize(100, 100) .into(target); } contactHolder.title.setText(contact.getmUserName()); //feedListRowHolder.genre.setText(Html.fromHtml(feedItem.getGenre())); } @Override public int getItemCount() { return (null != contactList ? contactList.size() : 0); } public void SaveImages(Bitmap bitmap,String profileName) { try { String root = Environment.getExternalStorageDirectory().getPath(); File myDir = new File(root +"/ContactProfileImages"); if (!myDir.exists()) { myDir.mkdirs(); } // String name = new Date().toString();= String name = profileName; File myDir1 = new File(myDir, name); if(!myDir1.exists()) { FileOutputStream out = new FileOutputStream(myDir1); bitmap.compress(Bitmap.CompressFormat.JPEG,100, out); out.flush(); out.close(); } } catch(Exception e){ // some action } //myDir1= imageFilePath1.getprofile(); } public class ContactHolder extends RecyclerView.ViewHolder { protected CircleImageView thumbnail; protected TextView title; public ContactHolder(View view) { super(view); this.thumbnail = (CircleImageView) view.findViewById(R.id.thumbnail); this.title = (TextView) view.findViewById(R.id.title); } } } ,并在下一次点击它被解雇。

联系适配器:

public class MainActivity extends AppCompatActivity implements GetContactsAsyncTask.ContactGetCallBack{

    private TextView txtuserName,txtmobile;
    private static final String TAG = "RecyclerViewExample";
    private static String KEY_SUCCESS1 = "Success";
    private List<Contact> contactList = new ArrayList<>();
    private CircleImageView profileImage;
    private RecyclerView recyclerView;
    JSONArray contactListArray;
    private ContactAdapter adapter;
    Toolbar toolbar;
    private NavigationView navigationView;
    private DrawerLayout drawerLayout;
    private SharedPreferences sharedpreferences;
    private String mUserId;
    private User mUser;
    private String url;
    private Intent mIntent;
    private UserTableHelper mDb;
    private Boolean firstTimeLogin,updateUser;
    private static final int MY_PERMISSIONS_REQUEST_CALL = 20;
    private ContactTableHelper contactDb;

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

        contactDb = new ContactTableHelper(MainActivity.this);
        mDb = new UserTableHelper(MainActivity.this);

        sharedpreferences = getSharedPreferences("UserId", Context.MODE_PRIVATE);

        mUserId = sharedpreferences.getString("userId","");

        sharedpreferences = getSharedPreferences("InitialLogin", Context.MODE_PRIVATE);

        firstTimeLogin = sharedpreferences.getBoolean("login",false);

        setupView();

        mUser = new User();
        sharedpreferences = getSharedPreferences("Url", Context.MODE_PRIVATE);

        url= sharedpreferences.getString("url","");

        contactList = new ArrayList<Contact>();

      //  new GetUserAsyncTask(mUserId).execute(mUserId);


            // get reference to the views
        txtuserName = (TextView) findViewById(R.id.txtusername);
        txtmobile = (TextView) findViewById(R.id.txtmobile);
        profileImage = (CircleImageView) findViewById(R.id.thumbnail);

                if (profileImage != null) {
                    profileImage.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            drawerLayout.closeDrawers();
                            Intent Intent = new Intent(MainActivity.this, ProfileActivity.class);
                            Intent.putExtra("url",url);
                            startActivity(Intent);
                        }
                    });
            }
        }

    void setupView() {


        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);


       navigationView = (NavigationView) findViewById(R.id.navigation_view);


       navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {
                drawerLayout.closeDrawers();
                menuItem.setChecked(true);

                FragmentManager fragmentManager = getSupportFragmentManager();

                switch (menuItem.getItemId()) {

                    case R.id.nav_menu_contacts:
                        // TODO - Do something

                       // ContactFragment fragment = new ContactFragment();
                     //   fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();

                        break;

                    case R.id.nav_menu_settings:

                        break;

                    case R.id.nav_log_out:

                        sharedpreferences = getSharedPreferences("UserId", Context.MODE_PRIVATE);

                        mUserId = sharedpreferences.getString("userId","");

                        finish();
                        Intent i = new Intent(MainActivity.this,LoginActivity.class);
                        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        startActivity(i);

                        break;

                    // TODO - Handle other items
                }
                return true;
            }
        });

        Toolbar toolbar = (Toolbar) findViewById(R.id.main_toolbar);
        TextView mTitle = (TextView) findViewById(R.id.toolbar_title);
        Toolbar.LayoutParams params = new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.MATCH_PARENT);
        params.gravity = Gravity.CENTER_HORIZONTAL;

        mTitle.setLayoutParams(params);
        if (toolbar != null) {
            toolbar.setTitle("");
            setSupportActionBar(toolbar);

        }

        if (toolbar != null) {

            toolbar.setNavigationIcon(R.drawable.ic_menu_white_24dp);
            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    drawerLayout.openDrawer(GravityCompat.START);
                    File sd = Environment.getExternalStorageDirectory();
                    File image = new File(sd+"/Profile","Profile_Image.jpg");
                    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
                    Bitmap bitmap = BitmapFactory.decodeFile(image.getPath(),bmOptions);

                    if(bitmap != null) {
                        profileImage.setImageBitmap(bitmap);
                    }
                    else {
                        profileImage.setImageDrawable(ContextCompat.getDrawable(MainActivity.this,R.drawable.ic_account_circle_white_48dp));
                    }
                }
            });
        }
    }

    @Override
    public void doPostExecute(JSONArray response) throws JSONException {

        contactListArray = response;

        contactDb = new ContactTableHelper(MainActivity.this);

        if (null == contactList) {
            contactList = new ArrayList<Contact>();
        }

        for (int i = 0; i < contactListArray.length(); i++) {
            JSONObject subObject1 = contactListArray.getJSONObject(i);

                Contact contact = new Contact();
                JSONObject subObject = subObject1;
                String contactName = subObject.getString("user_name");
                //name of the attribute in response
                String contactId = subObject.getString("user_id");
                String contactMobile = subObject.getString("mobile_no");
                String contactEmailId = subObject.getString("email_id");
                String contactProfile = subObject.getString("profile_image");
                String fullName = subObject.getString("full_name");
                String jobTitle = subObject.getString("job_title");
                String homeAddress = subObject.getString("home_address");
                String workPhone = subObject.getString("work_phone");
                String workAddress = subObject.getString("work_address");

                contact.setmThumbnail(contactProfile);
                contact.setmUserName(contactName);
                contact.setmMobileNo(contactMobile);
                contact.setmEmailId(contactEmailId);
                contact.setmProfileImage(contactProfile);
                contact.setContactId(contactId);
                contact.setmHomeAddress(homeAddress);
                contact.setmFullName(fullName);
                contact.setmJobTitle(jobTitle);
                contact.setmWorkAddress(workAddress);
                contact.setmWorkPhone(workPhone);

                contactList.add(contact);//adding string to arraylist

            contactDb.addContact(new Contact(contactId,contactName,contactMobile,contactEmailId,contactProfile,fullName,jobTitle,workAddress,workPhone,homeAddress));
        }

        adapter = new ContactAdapter(MainActivity.this, contactList);
        recyclerView.setAdapter(adapter);
    }


    public interface ClickListener {
        void onClick(View view, int position);

        void onLongClick(View view, int position);
    }

    public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {

        private GestureDetector gestureDetector;
        private MainActivity.ClickListener mclickListener;

        public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final MainActivity.ClickListener clickListener)
        {
            this.mclickListener = clickListener;
            gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener()
            {
                @Override
                public boolean onSingleTapUp(MotionEvent e) {
                    return true;
                }

                @Override
                public void onLongPress(MotionEvent e)
                {
                    View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                    if (child != null && clickListener != null)
                    {
                        mclickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child));
                    }
                }
            });
        }

        @Override
        public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {

            View child = rv.findChildViewUnder(e.getX(), e.getY());
            if (child != null && mclickListener != null && gestureDetector.onTouchEvent(e))
            {
                mclickListener.onClick(child, rv.getChildAdapterPosition(child));
            }
            return false;
        }

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

        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept)
        {

        }
    }

    @Override
    public void onResume()
    {
        super.onResume();

        if(!firstTimeLogin)
        {
            contactList.clear();
            contactList = contactDb.getAllContacts();
            mUser = mDb.getUser(mUserId);

        }
        else {
            new GetUserAsyncTask(mUserId).execute(mUserId);
            new GetContactsAsyncTask(this, MainActivity.this, mUserId).execute();

            firstTimeLogin = false;

            SharedPreferences.Editor editor = getSharedPreferences("InitialLogin",MODE_PRIVATE).edit();
            editor.putBoolean("login",firstTimeLogin);
            editor.commit();
        }

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(MainActivity.this);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        adapter = new ContactAdapter(MainActivity.this, contactList);
        recyclerView.setAdapter(adapter);

        recyclerView.addOnItemTouchListener(new RecyclerTouchListener(MainActivity.this, recyclerView, new ClickListener() {
            @Override
            public void onClick(View view, int position) {
                final Contact contact = contactList.get(position);

                // custom dialog
                final Dialog dialog = new Dialog(MainActivity.this);
                dialog.setCanceledOnTouchOutside(true);
                dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                dialog.setContentView(R.layout.custom);
                final Window window = dialog.getWindow();

                WindowManager.LayoutParams wlp =window.getAttributes();
                wlp.gravity = Gravity.CENTER_HORIZONTAL|Gravity.TOP;
                wlp.y=320;
                window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                window.setAttributes(wlp);

                // set the custom dialog components - text, image and button
                TextView txtusername = (TextView) dialog.findViewById(R.id.txtusername);
                TextView txtmobile = (TextView) dialog.findViewById(R.id.txtmobile);
                TextView txtemail = (TextView) dialog.findViewById(R.id.txtemail);

                txtusername.setText(contact.getmUserName());
                txtemail.setText(contact.getmEmailId());
                txtmobile.setText(contact.getmMobileNo());

                SquareImageView image = (SquareImageView) dialog.findViewById(R.id.image);
                ImageView image1 = (ImageView) dialog.findViewById(R.id.image1);
                ImageView image2 = (ImageView) dialog.findViewById(R.id.image2);
                ImageView image3 = (ImageView) dialog.findViewById(R.id.image3);

                if(contact.getmProfileImage().equals(""))

                {
                    image.setImageDrawable(ContextCompat.getDrawable(MainActivity.this,R.drawable.profile_icon));
                }
                else {
                    File file = new File(Environment.getExternalStorageDirectory() + "/ContactProfileImages/" + contact.getmProfileImage());
                    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
                    Bitmap bitmap = BitmapFactory.decodeFile(file.getPath(), bmOptions);

                    image.setImageBitmap(bitmap);
                }

                image1.setImageResource(R.drawable.ic_call_black_24dp);
                image2.setImageResource(R.drawable.ic_textsms_black_24dp);
                image3.setImageResource(R.drawable.ic_email_black_24dp);

                image2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        Uri sms_uri = Uri.parse("smsto:" + contact.getmMobileNo());
                        Intent sms_intent = new Intent(Intent.ACTION_SENDTO, sms_uri);
                        startActivity(sms_intent);
                        dialog.dismiss();

                    }
                });

                image1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        if (ContextCompat.checkSelfPermission(MainActivity.this,
                                Manifest.permission.CALL_PHONE)
                                != PackageManager.PERMISSION_GRANTED) {

                                ActivityCompat.requestPermissions(MainActivity.this,
                                        new String[]{Manifest.permission.CALL_PHONE},
                                        MY_PERMISSIONS_REQUEST_CALL);

                            }
                        else {

                            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + contact.getmMobileNo()));
                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            startActivity(intent);
                            dialog.dismiss();
                        }

                    }
                });

                image3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(Intent.ACTION_SENDTO);
                        intent.setData(Uri.parse("mailto:")); // only email apps should handle this
                        intent.putExtra(Intent.EXTRA_EMAIL,contact.getmEmailId());
                        intent.putExtra(Intent.EXTRA_SUBJECT,"");
                        if (intent.resolveActivity(getPackageManager()) != null) {
                            startActivity(intent);
                        }
                    }
                });

                Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
                // if button is clicked, view all information custom dialog

                dialogButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        Intent intent = new Intent(MainActivity.this,DetailViewActivity.class);
                        intent.putExtra("contact",contact);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        startActivity(intent);

                    }
                });
                dialog.show();
            }

            @Override
            public void onLongClick(View view, int position) {

            }
        }));

    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_CALL: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    try {

                        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"));
                        startActivity(intent);
                    }
                    catch (SecurityException e)
                    {

                    }
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                return;
            }
        }
    }
}

活性:

#Quotation Control Unit
        for i in words:
            try:
                #If the file's first character is a quotation mark keep looking
                #for the other one
                if(i[0] == '"'):
                    #This for loop checks every character in the current(i) word
                    for idx in i:
                        #If the quotation mark is found in the same word which
                        #the first quotation mark is in, then delete the
                        #quotation marks and print the word into the file
                        #without them.
                        if(i[idx] == '"'):
                            words[words.index(i)] = i[1:(len(i) - 2)]
                            raise Done

                        #If the closing quotation mark couldn't be found in the
                        #same word, go to the other word and search for it
                        if('"' not in i[1:]):
                            searched_words = 1
                            #Start looking for the words which comes after the
                            #word, which hosts the first quotation mark
                            for a in words[(words.index(i) + 1):]:
                                searched_words += 1
                                #If the second quotation mark is found like this:
                                #  "Ärztin "Ka.......
                                #Throw an error window
                                if (a[0] == '"'):
                                    iP = NoFileNameError()
                                    ip.setupUiInappropiateText()
                                    ip.show()

                                #If the second quotation mark is found then
                                if (a[(len(a) - 1)] == '"'):
                                    #combine the text between them
                                    words[words.index(i)] = i[1:] + a[:
                                                        (len(xd) - 1)]

                                    #After this is done, delete the strings
                                    #which comes after the string which hosts
                                    #the first quotation mark
                                    #E.g a = ['"a', 'b', 'c"']
                                    #a[0] = 'abc'
                                    #del b,c
                                    #final list = a = ['abc']
                                    for s in words[(words.index(i) + 1):(searched_words + 1)]

                                        del words[words.index(s)]

                                    raise Done


            except Done:
                continue

这里出了什么问题?

2 个答案:

答案 0 :(得分:1)

首先

替换MainActivity

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.notificationdemo.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements GetContactsAsyncTask.ContactGetCallBack{

    private TextView txtuserName,txtmobile;
    private static final String TAG = "RecyclerViewExample";
    private static String KEY_SUCCESS1 = "Success";
    private List<Contact> contactList = new ArrayList<>();
    private CircleImageView profileImage;
    private RecyclerView recyclerView;
    JSONArray contactListArray;
    private ContactAdapter adapter;
    Toolbar toolbar;
    private NavigationView navigationView;
    private DrawerLayout drawerLayout;
    private SharedPreferences sharedpreferences;
    private String mUserId;
    private User mUser;
    private String url;
    private Intent mIntent;
    private UserTableHelper mDb;
    private Boolean firstTimeLogin,updateUser;
    private static final int MY_PERMISSIONS_REQUEST_CALL = 20;
    private ContactTableHelper contactDb;

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

        contactDb = new ContactTableHelper(MainActivity.this);
        mDb = new UserTableHelper(MainActivity.this);

        sharedpreferences = getSharedPreferences("UserId", Context.MODE_PRIVATE);

        mUserId = sharedpreferences.getString("userId","");

        sharedpreferences = getSharedPreferences("InitialLogin", Context.MODE_PRIVATE);

        firstTimeLogin = sharedpreferences.getBoolean("login",false);

        setupView();

        mUser = new User();
        sharedpreferences = getSharedPreferences("Url", Context.MODE_PRIVATE);

        url= sharedpreferences.getString("url","");

        contactList = new ArrayList<Contact>();

      //  new GetUserAsyncTask(mUserId).execute(mUserId);


            // get reference to the views
        txtuserName = (TextView) findViewById(R.id.txtusername);
        txtmobile = (TextView) findViewById(R.id.txtmobile);
        profileImage = (CircleImageView) findViewById(R.id.thumbnail);

                if (profileImage != null) {
                    profileImage.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            drawerLayout.closeDrawers();
                            Intent Intent = new Intent(MainActivity.this, ProfileActivity.class);
                            Intent.putExtra("url",url);
                            startActivity(Intent);
                        }
                    });
            }
        }

    void setupView() {


        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);


       navigationView = (NavigationView) findViewById(R.id.navigation_view);


       navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {
                drawerLayout.closeDrawers();
                menuItem.setChecked(true);

                FragmentManager fragmentManager = getSupportFragmentManager();

                switch (menuItem.getItemId()) {

                    case R.id.nav_menu_contacts:
                        // TODO - Do something

                       // ContactFragment fragment = new ContactFragment();
                     //   fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();

                        break;

                    case R.id.nav_menu_settings:

                        break;

                    case R.id.nav_log_out:

                        sharedpreferences = getSharedPreferences("UserId", Context.MODE_PRIVATE);

                        mUserId = sharedpreferences.getString("userId","");

                        finish();
                        Intent i = new Intent(MainActivity.this,LoginActivity.class);
                        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        startActivity(i);

                        break;

                    // TODO - Handle other items
                }
                return true;
            }
        });

        Toolbar toolbar = (Toolbar) findViewById(R.id.main_toolbar);
        TextView mTitle = (TextView) findViewById(R.id.toolbar_title);
        Toolbar.LayoutParams params = new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.MATCH_PARENT);
        params.gravity = Gravity.CENTER_HORIZONTAL;

        mTitle.setLayoutParams(params);
        if (toolbar != null) {
            toolbar.setTitle("");
            setSupportActionBar(toolbar);

        }

        if (toolbar != null) {

            toolbar.setNavigationIcon(R.drawable.ic_menu_white_24dp);
            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    drawerLayout.openDrawer(GravityCompat.START);
                    File sd = Environment.getExternalStorageDirectory();
                    File image = new File(sd+"/Profile","Profile_Image.jpg");
                    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
                    Bitmap bitmap = BitmapFactory.decodeFile(image.getPath(),bmOptions);

                    if(bitmap != null) {
                        profileImage.setImageBitmap(bitmap);
                    }
                    else {
                        profileImage.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_account_circle_white_48dp));
                    }
                }
            });
        }
    }

    @Override
    public void doPostExecute(JSONArray response) throws JSONException {

        contactListArray = response;

        contactDb = new ContactTableHelper(MainActivity.this);

        if (null == contactList) {
            contactList = new ArrayList<Contact>();
        }

        for (int i = 0; i < contactListArray.length(); i++) {
            JSONObject subObject1 = contactListArray.getJSONObject(i);

                Contact contact = new Contact();
                JSONObject subObject = subObject1;
                String contactName = subObject.getString("user_name");
                //name of the attribute in response
                String contactId = subObject.getString("user_id");
                String contactMobile = subObject.getString("mobile_no");
                String contactEmailId = subObject.getString("email_id");
                String contactProfile = subObject.getString("profile_image");
                String fullName = subObject.getString("full_name");
                String jobTitle = subObject.getString("job_title");
                String homeAddress = subObject.getString("home_address");
                String workPhone = subObject.getString("work_phone");
                String workAddress = subObject.getString("work_address");

                contact.setmThumbnail(contactProfile);
                contact.setmUserName(contactName);
                contact.setmMobileNo(contactMobile);
                contact.setmEmailId(contactEmailId);
                contact.setmProfileImage(contactProfile);
                contact.setContactId(contactId);
                contact.setmHomeAddress(homeAddress);
                contact.setmFullName(fullName);
                contact.setmJobTitle(jobTitle);
                contact.setmWorkAddress(workAddress);
                contact.setmWorkPhone(workPhone);

                contactList.add(contact);//adding string to arraylist

            contactDb.addContact(new Contact(contactId,contactName,contactMobile,contactEmailId,contactProfile,fullName,jobTitle,workAddress,workPhone,homeAddress));
        }

        adapter = new ContactAdapter(MainActivity.this, contactList);
        recyclerView.setAdapter(adapter);
    }


    public interface ClickListener {
        void onClick(View view, int position);

        void onLongClick(View view, int position);
    }

    public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {

        private GestureDetector gestureDetector;
        private MainActivity.ClickListener mclickListener;

        public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final MainActivity.ClickListener clickListener)
        {
            this.mclickListener = clickListener;
            gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener()
            {
                @Override
                public boolean onSingleTapUp(MotionEvent e) {
                    return true;
                }

                @Override
                public void onLongPress(MotionEvent e)
                {
                    View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                    if (child != null && clickListener != null)
                    {
                        mclickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child));
                    }
                }
            });
        }

        @Override
        public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {

            View child = rv.findChildViewUnder(e.getX(), e.getY());
            if (child != null && mclickListener != null && gestureDetector.onTouchEvent(e))
            {
                mclickListener.onClick(child, rv.getChildAdapterPosition(child));
            }
            return false;
        }

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

        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept)
        {

        }
    }

    @Override
    public void onResume()
    {
        super.onResume();

        if(!firstTimeLogin)
        {
            contactList.clear();
            contactList = contactDb.getAllContacts();
            mUser = mDb.getUser(mUserId);

        }
        else {
            new GetUserAsyncTask(mUserId).execute(mUserId);
            new GetContactsAsyncTask(this, MainActivity.this, mUserId).execute();

            firstTimeLogin = false;

            SharedPreferences.Editor editor = getSharedPreferences("InitialLogin",MODE_PRIVATE).edit();
            editor.putBoolean("login",firstTimeLogin);
            editor.commit();
        }

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(MainActivity.this);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        adapter = new ContactAdapter(MainActivity.this, contactList);
        recyclerView.setAdapter(adapter);

        recyclerView.addOnItemTouchListener(new RecyclerTouchListener(MainActivity.this, recyclerView, new ClickListener() {
            @Override
            public void onClick(View view, int position) {
                final Contact contact = contactList.get(position);

                // custom dialog

            }

            @Override
            public void onLongClick(View view, int position) {

            }
        }));

    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_CALL: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    try {

                        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"));
                        startActivity(intent);
                    }
                    catch (SecurityException e)
                    {

                    }
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                return;
            }
        }
    }
}

更换适配器

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.notificationdemo.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.annotation.Target;

public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ContactHolder> {


    private List<Contact> contactList;
    File myDir1;
    private Activity mContext;

    private Boolean fileExists;
    private File file;

    public ContactAdapter(Activity context, List<Contact> contactList) {
        this.contactList = contactList;
        this.mContext = context;
    }

    @Override
    public ContactHolder onCreateViewHolder(ViewGroup viewGroup, int i) {

        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_layout,null);
       ContactHolder mh = new ContactHolder(v);

        return mh;
    }

    @Override
    public void onBindViewHolder(final ContactHolder contactHolder, int i) {

        final Contact contact = contactList.get(i);
      //  Log.e("Imagename",""+"http://xesoftwares.co.in/contactsapi/profile_images/85368a5bbd6cffba8a3aa202a80563a2.jpg");//+feedItem.getThumbnail());

        Target target = new Target() {

            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {

                // your code here ...
                    contactHolder.thumbnail.setImageBitmap(bitmap);

                Log.e("ProfileImage", contact.getmProfileImage());

                    SaveImages(bitmap, contact.getmProfileImage());

            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {
                contactHolder.thumbnail.setImageDrawable(errorDrawable);
                // do error handling as required
            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {
               contactHolder.thumbnail.setImageDrawable(placeHolderDrawable);
            }
        };

        contactHolder.thumbnail.setTag(target);

        String url = ServiceUrl.getBaseUrl() + ServiceUrl.getImageUserUrl() + contact.getmProfileImage();

        Log.e("url",url);

        if(contact.getmProfileImage().equals(""))

        {

            file = new File("");

            fileExists = file.exists();

            contactHolder.thumbnail.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_account_circle_black_48dp));
        }
        else {

            file = new File(Environment.getExternalStorageDirectory() + "/ContactProfileImages/" + contact.getmProfileImage());

            fileExists = file.exists();
        }

        if(fileExists)
        {

            Log.e("fileExists",file.getAbsolutePath());

            BitmapFactory.Options bmOptions = new BitmapFactory.Options();
            Bitmap bitmap = BitmapFactory.decodeFile(file.getPath(), bmOptions);
            contactHolder.thumbnail.setImageBitmap(bitmap);

        }

        else {

            Log.e("Picasso",file.getAbsolutePath());

            Picasso.with(mContext).load(url)
                    .error(R.drawable.ic_account_circle_black_24dp)
                    .placeholder(R.drawable.ic_account_circle_black_24dp)
                    .resize(100, 100)
                    .into(target);


        }

        contactHolder.title.setText(contact.getmUserName());
        //feedListRowHolder.genre.setText(Html.fromHtml(feedItem.getGenre()));





    }

    @Override
    public int getItemCount() {
        return (null != contactList ? contactList.size() : 0);
    }

    public void SaveImages(Bitmap bitmap,String profileName)
    {

        try {
            String root = Environment.getExternalStorageDirectory().getPath();
            File myDir = new File(root +"/ContactProfileImages");

            if (!myDir.exists()) {
                myDir.mkdirs();
            }

            // String name = new Date().toString();=
            String name = profileName;
            File myDir1 = new File(myDir, name);
            if(!myDir1.exists()) {
                FileOutputStream out = new FileOutputStream(myDir1);
                bitmap.compress(Bitmap.CompressFormat.JPEG,100, out);

                out.flush();
                out.close();
            }


        } catch(Exception e){
            // some action
        }

         //myDir1= imageFilePath1.getprofile();

    }


    public class ContactHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        protected CircleImageView thumbnail;
        protected TextView title;

        public ContactHolder(View view) {
            super(view);
            this.thumbnail = (CircleImageView) view.findViewById(R.id.thumbnail);
            this.title = (TextView) view.findViewById(R.id.title);
            view.setOnClickListener(this);





        }

        @Override
        public void onClick(View v) {

            final Contact contact = contactList.get(getAdapterPosition());

            final Dialog dialog = new Dialog(mContext);
            dialog.setCanceledOnTouchOutside(true);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setContentView(R.layout.custom);
            final Window window = dialog.getWindow();

            WindowManager.LayoutParams wlp =window.getAttributes();
            wlp.gravity = Gravity.CENTER_HORIZONTAL|Gravity.TOP;
            wlp.y=320;
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            window.setAttributes(wlp);

            // set the custom dialog components - text, image and button
            TextView txtusername = (TextView) dialog.findViewById(R.id.txtusername);
            TextView txtmobile = (TextView) dialog.findViewById(R.id.txtmobile);
            TextView txtemail = (TextView) dialog.findViewById(R.id.txtemail);

            txtusername.setText(contact.getmUserName());
            txtemail.setText(contact.getmEmailId());
            txtmobile.setText(contact.getmMobileNo());

            SquareImageView image = (SquareImageView) dialog.findViewById(R.id.image);
            ImageView image1 = (ImageView) dialog.findViewById(R.id.image1);
            ImageView image2 = (ImageView) dialog.findViewById(R.id.image2);
            ImageView image3 = (ImageView) dialog.findViewById(R.id.image3);

            if(contact.getmProfileImage().equals(""))

            {
                image.setImageDrawable(ContextCompat.getDrawable(mContext,R.drawable.profile_icon));
            }
            else {
                File file = new File(Environment.getExternalStorageDirectory() + "/ContactProfileImages/" + contact.getmProfileImage());
                BitmapFactory.Options bmOptions = new BitmapFactory.Options();
                Bitmap bitmap = BitmapFactory.decodeFile(file.getPath(), bmOptions);

                image.setImageBitmap(bitmap);
            }

            image1.setImageResource(R.drawable.ic_call_black_24dp);
            image2.setImageResource(R.drawable.ic_textsms_black_24dp);
            image3.setImageResource(R.drawable.ic_email_black_24dp);

            image2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    Uri sms_uri = Uri.parse("smsto:" + contact.getmMobileNo());
                    Intent sms_intent = new Intent(Intent.ACTION_SENDTO, sms_uri);
                    mContext.startActivity(sms_intent);
                    dialog.dismiss();

                }
            });

            image1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    if (ContextCompat.checkSelfPermission(mContext,
                            Manifest.permission.CALL_PHONE)
                            != PackageManager.PERMISSION_GRANTED) {

                        ActivityCompat.requestPermissions(mContext,
                                new String[]{Manifest.permission.CALL_PHONE},
                                MY_PERMISSIONS_REQUEST_CALL);

                    }
                    else {

                        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + contact.getmMobileNo()));
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        mContext.startActivity(intent);
                        dialog.dismiss();
                    }

                }
            });

            image3.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(Intent.ACTION_SENDTO);
                    intent.setData(Uri.parse("mailto:")); // only email apps should handle this
                    intent.putExtra(Intent.EXTRA_EMAIL,contact.getmEmailId());
                    intent.putExtra(Intent.EXTRA_SUBJECT,"");
                    if (intent.resolveActivity(getPackageManager()) != null) {
                        mContext.startActivity(intent);
                    }
                }
            });

            Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
            // if button is clicked, view all information custom dialog

            dialogButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    Intent intent = new Intent(mContext,DetailViewActivity.class);
                    intent.putExtra("contact",contact);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    mContext.startActivity(intent);

                }
            });
            dialog.show();



        }
    }
}

答案 1 :(得分:-1)

尝试此代码:在自定义对话框布局中选择“关闭”按钮。

Button cancel = (Button) dialog.findViewById(R.id.cancel);

cancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
    dialog.dismiss();

}
});