如何用用户表单库中选择的另一个替换ImageView中的图像?

时间:2017-10-01 16:21:23

标签: java android

我希望我的应用更改用户在触摸ImageView(占位符)时从图库中选择的个人资料照片。我当前的代码会打开图库,但只要您选择了图片,该应用就会停止工作。此外,它在导航栏中。所以,如果你们中的任何人都可以提供帮助,那就太棒了。

这是我的MainActivity.java(您可以忽略不需要的部分)

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {
private static final int SELECT_PHOTO = 100;
private ImageView chooseImage;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);


    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);

    ImageView startEmergency = (ImageView) (findViewById(R.id.start_emergency));

    startEmergency.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent emergencyIntent = new Intent(MainActivity.this, EmergencyActActivity.class);

            startActivity(emergencyIntent);
        }
    });

    TextView myHealth = (TextView) (findViewById(R.id.myHealth));

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

            Intent healthIntent = new Intent(MainActivity.this, HealthActivity.class);

            startActivity(healthIntent);
        }
    });

   /* TextView browse=(TextView) (findViewById(R.id.browse));

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

            Intent browseIntent=new Intent(MainActivity.this, BrowseActivity.class);

            startActivity(browseIntent);
        }
    });*/

    TextView myAccount = (TextView) (findViewById(R.id.myAccount));

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

            Intent accountIntent = new Intent(MainActivity.this, AccountActivity.class);
            startActivity(accountIntent);
        }
    });

    ImageView imageView = (ImageView) findViewById(R.id.imageButton);

    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            openGallery();
        }
    });

}
private void openGallery() {
    Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
    photoPickerIntent.setType("image/*");
    startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}



@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == 1 && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        ImageView imageView = (ImageView) findViewById(R.id.imageButton);
        imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

    }
}

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
        View v = getCurrentFocus();
        if (v instanceof EditText) {
            EditText edit = ((EditText) v);
            Rect outR = new Rect();
            edit.getGlobalVisibleRect(outR);
            Boolean isKeyboardOpen = !outR.contains((int)ev.getRawX(), (int)ev.getRawY());
            System.out.print("Is Keyboard? " + isKeyboardOpen);
            if (isKeyboardOpen) {
                System.out.print("Entro al IF");
                edit.clearFocus();
                InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(edit.getWindowToken(), 0);
            }

            edit.setCursorVisible(!isKeyboardOpen);

        }
    }
    return super.dispatchTouchEvent(ev);
}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);

    MenuItem searchItem = menu.findItem(R.id.search);
    MenuItem searchMenuItem = menu.findItem(R.id.search);
    if (searchMenuItem == null) {
        return true;
    }

    searchItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            // Create a Uri from an intent string. Use the result to create an Intent.
            Uri gmmIntentUri = Uri.parse("geo:0,0?q=hospitals");

            Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
            mapIntent.setPackage("com.google.android.apps.maps");

            startActivity(mapIntent);

            return true;
        }
    });

    return true;


}

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



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

    if (id == R.id.nav_camera) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

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

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

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

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

    }

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

和navigation_header.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="180dp"
    android:background="@android:color/holo_red_light">

    <EditText
        android:id="@+id/Name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:cursorVisible="false"
        android:text="Name"
        android:background="@null"
        android:imeOptions="actionSend"
        android:inputType="text"
        android:textSize="28dp"
        android:textColor="#ffffff"
        android:layout_marginBottom="30dp"
        android:layout_alignParentBottom="true"
        android:layout_alignLeft="@+id/imageButton"
         />
    <ImageView
        android:id="@+id/imageButton"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:layout_marginLeft="13dp"
        android:layout_marginStart="13dp"
        android:background="@drawable/img"
        android:layout_marginBottom="9dp"
        android:layout_above="@+id/Name"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

记录

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.admin.thehealthapp, PID: 5301
              java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=100, result=-1, data=Intent { dat=content://media/external/images/media/37329 }} to activity {com.example.admin.thehealthapp/com.example.admin.thehealthapp.MainActivity}: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/37329 from pid=5301, uid=10081 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
                  at android.app.ActivityThread.deliverResults(ActivityThread.java:3813)
                  at android.app.ActivityThread.handleSendResult(ActivityThread.java:3856)
                  at android.app.ActivityThread.access$1500(ActivityThread.java:155)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:148)
                  at android.app.ActivityThread.main(ActivityThread.java:5539)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
               Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/37329 from pid=5301, uid=10081 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
                  at android.os.Parcel.readException(Parcel.java:1620)
                  at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)
                  at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
                  at android.content.ContentProviderProxy.query(ContentProviderNative.java:421)
                  at android.content.ContentResolver.query(ContentResolver.java:524)
                  at android.content.ContentResolver.query(ContentResolver.java:438)
                  at com.example.admin.thehealthapp.MainActivity.onActivityResult(MainActivity.java:117)
                  at android.app.Activity.dispatchActivityResult(Activity.java:6498)
                  at android.app.ActivityThread.deliverResults(ActivityThread.java:3809)
                  at android.app.ActivityThread.handleSendResult(ActivityThread.java:3856) 
                  at android.app.ActivityThread.access$1500(ActivityThread.java:155) 
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470) 
                  at android.os.Handler.dispatchMessage(Handler.java:102) 
                  at android.os.Looper.loop(Looper.java:148) 
                  at android.app.ActivityThread.main(ActivityThread.java:5539) 
                  at java.lang.reflect.Method.invoke(Native Method) 
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

0 个答案:

没有答案