Draw circle on ImageView at touched point - java

I am trying to draw circle on ImageView at touched point but it draws at left top corner.
My code is
ImageView imageView;
private static int RESULT_LOAD_IMAGE = 1;
Bitmap bmp;
float touchY;
float touchX;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchX = event.getX();
touchY = event.getY();
imageView.setImageBitmap(drawCircle());
break;
default:
break;
}
return false;
}
});
}
private Bitmap drawCircle() {
Bitmap bitmap = bmp.copy(Bitmap.Config.ARGB_4444, true);
bitmap.setPixel(imageView.getWidth(), imageView.getHeight(), 0);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.RED);
canvas.drawCircle(touchX, touchY, 100, paint);
return bitmap;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.getimage:
pickImage();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
private void pickImage() {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null){
Uri uri = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, filePath, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePath[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
bmp = BitmapFactory.decodeFile(picturePath);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
and xml is
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/ic_launcher" />
</RelativeLayout>
I am not getting what is wrong. I want to draw circle at touched point. Any help will be appreciated.

If you would create a new bitmap with the size of ImageView this code would work fine.
However the "bmp" bitmap is probably much larger then the ImageView and is scaled. That's why you get distorted result.

Related

how to put taken image in specific image view

I have an activity that contain a grid view which contain 3 card view each has an image view I want to setonclick mistenr that put the taken iamge from camera to the selected image view.
How can I fix this? By the way I'm using the same code for the three image view the issue is in the in activityresult method and I can't change it.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".inspection.ImageActivity">
<View
android:id="#+id/bg_top_header9"
android:layout_width="match_parent"
android:layout_height="193dp"
android:background="#drawable/ic_bg_topheader"
app:layout_constraintBottom_toTopOf="#+id/gridLayout"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<GridLayout
android:id="#+id/gridLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="110dp"
android:alignmentMode="alignMargins"
android:columnCount="1"
android:columnOrderPreserved="false"
android:padding="14dp"
android:rowCount="3"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintVertical_bias="0.343"
app:layout_editor_absoluteX="0dp">
<androidx.cardview.widget.CardView
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_rowWeight="1"
android:layout_columnWeight="1"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:background="#color/whiteCardColor"
app:cardCornerRadius="20dp"
app:cardElevation="5dp">
<ImageView
android:id="#+id/img1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
app:srcCompat="#drawable/ic_img" />
</androidx.cardview.widget.CardView>
<androidx.cardview.widget.CardView
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_rowWeight="1"
android:layout_columnWeight="1"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:background="#color/whiteCardColor"
app:cardCornerRadius="20dp"
app:cardElevation="5dp">
<ImageView
android:id="#+id/img2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
app:srcCompat="#drawable/ic_img" />
</androidx.cardview.widget.CardView>
<androidx.cardview.widget.CardView
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_rowWeight="1"
android:layout_columnWeight="1"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="16dp"
android:background="#color/whiteCardColor"
app:cardCornerRadius="20dp"
app:cardElevation="5dp">
<ImageView
android:id="#+id/img3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
app:srcCompat="#drawable/ic_img" />
</androidx.cardview.widget.CardView>
</GridLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
and this is the java class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image);
bgTopHeader9 = findViewById(R.id.bg_top_header9);
gridLayout = findViewById(R.id.gridLayout);
img1 = findViewById(R.id.img1);
img2 = findViewById(R.id.img2);
img3 = findViewById(R.id.img3);
img1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(ImageActivity.this);
builder.setPositiveButton(R.string.takepic, (dialog, which) -> {
try {
captureImage();
} catch (IOException e) {
e.printStackTrace();
}
}).setNegativeButton("Delete", (dialog, which) -> {
if (imgFile.exists()) {
if (imgFile.delete())
Toast.makeText(ImageActivity.this, mCurrentPhotoPath + "deleted",
Toast.LENGTH_SHORT).show();
img1.setImageResource(R.drawable.ic_img);
}
}).setNeutralButton("Cancle ", (dialog, which) -> dialog.cancel());
final AlertDialog dialog = builder.create();
LayoutInflater inflater = getLayoutInflater();
#SuppressLint("InflateParams") View dialogLayout = inflater.inflate(R.layout.diag_layout, null);
dialog.setView(dialogLayout);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setOnShowListener(d -> {
if (!(img1.getDrawable() == getResources().getDrawable(R.drawable.ic_img))) {
Bitmap myBitmap1 = BitmapFactory.decodeFile(mCurrentPhotoPath);
ImageView myImage = dialog.findViewById(R.id.image);
myImage.setImageBitmap(myBitmap1);
}
});
dialog.show();
}
});
img2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(ImageActivity.this);
builder.setPositiveButton(R.string.takepic, (dialog, which) -> {
try {
captureImage();
} catch (IOException e) {
e.printStackTrace();
}
}).setNegativeButton("Delete", (dialog, which) -> {
if (imgFile.exists()) {
if (imgFile.delete())
Toast.makeText(ImageActivity.this, mCurrentPhotoPath + "deleted", Toast.LENGTH_SHORT).show();
img2.setImageResource(R.drawable.ic_img);
}
}).setNeutralButton("Cancle ", (dialog, which) -> dialog.cancel());
final AlertDialog dialog = builder.create();
LayoutInflater inflater = getLayoutInflater();
#SuppressLint("InflateParams") View dialogLayout = inflater.inflate(R.layout.diag_layout, null);
dialog.setView(dialogLayout);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setOnShowListener(d -> {
if (!(img2.getDrawable() == getResources().getDrawable(R.drawable.ic_img))) {
Bitmap myBitmap1 = BitmapFactory.decodeFile(mCurrentPhotoPath);
ImageView myImage = dialog.findViewById(R.id.image);
myImage.setImageBitmap(myBitmap1);
}
});
dialog.show();
}
});
img3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(ImageActivity.this);
builder.setPositiveButton(R.string.takepic, (dialog, which) -> {
try {
captureImage();
} catch (IOException e) {
e.printStackTrace();
}
}).setNegativeButton("Delete", (dialog, which) -> {
if (imgFile.exists()) {
if (imgFile.delete())
Toast.makeText(ImageActivity.this, mCurrentPhotoPath + " deleted", Toast.LENGTH_SHORT).show();
img3.setImageResource(R.drawable.ic_img);
}
}).setNeutralButton(R.string.cancle_string, (dialog, which) -> dialog.cancel());
final AlertDialog dialog = builder.create();
LayoutInflater inflater = getLayoutInflater();
#SuppressLint("InflateParams") View dialogLayout = inflater.inflate(R.layout.diag_layout, null);
dialog.setView(dialogLayout);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setOnShowListener(d -> {
if (!(img3.getDrawable() == getResources().getDrawable(R.drawable.ic_img))) {
Bitmap myBitmap1 = BitmapFactory.decodeFile(mCurrentPhotoPath);
ImageView myImage = dialog.findViewById(R.id.image);
myImage.setImageBitmap(myBitmap1);
}
});
dialog.show();
}
});
}
private void Showimage() {
img1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) throws IndexOutOfBoundsException {
try {
AlertDialog.Builder builder = new AlertDialog.Builder(ImageActivity.this);
builder.setPositiveButton("cancel ", (dialog, which) -> {
dialog.cancel();
}).setNegativeButton("Delete ", (dialog, which) -> {
img1.setImageResource(R.drawable.ic_img);
option = false;
});
final AlertDialog dialog = builder.create();
LayoutInflater inflater = getLayoutInflater();
#SuppressLint("InflateParams") View dialogLayout = inflater.inflate(R.layout.diag_layout, null);
dialog.setView(dialogLayout);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setOnShowListener(d -> {
if (imgFile.exists()) {
Bitmap myBitmap1 = BitmapFactory.decodeFile(mCurrentPhotoPath);
ImageView myImage = dialog.findViewById(R.id.image);
myImage.setImageBitmap(myBitmap1);
}
});
dialog.show();
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
});
}
private void captureImage() throws IOException {
option = true;
String[] perms = {Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE};
if (EasyPermissions.hasPermissions(this, perms)) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
photoFile = createImageFile();
Uri photoURI = FileProvider.getUriForFile(ImageActivity.this, "com.xdev.pfe.utils.fileprovider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAPTURE_IMAGE_REQUEST);
} else {
EasyPermissions.requestPermissions(this, "We need permissions because this and that", 123, perms);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAPTURE_IMAGE_REQUEST && resultCode == RESULT_OK) {
#SuppressWarnings("unused") Bitmap myBitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
AlertDialog.Builder builder = new AlertDialog.Builder(ImageActivity.this);
builder.setPositiveButton("save ", (dialog, which) -> {
File imgFile = new File(mCurrentPhotoPath);
if (imgFile.exists()) {
byte[] imageData = null;
try {
final int THUMBNAIL_SIZE = 1024;
FileInputStream fis = new FileInputStream(imgFile);
Bitmap imageBitmap = BitmapFactory.decodeStream(fis);
imageBitmap = Bitmap.createScaledBitmap(imageBitmap, THUMBNAIL_SIZE, THUMBNAIL_SIZE, false);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
imageData = baos.toByteArray();
} catch (Exception ex) {
}
Bitmap bmp = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
img1.setImageBitmap(bmp);
System.out.println(paths);
}
}).setNegativeButton(R.string.recapture_string, (dialog, which) -> {
try {
captureImage();
} catch (IOException e) {
e.printStackTrace();
}
}).setNeutralButton(R.string.cancle_string, (dialog, which) -> dialog.cancel());
Toast.makeText(this, mCurrentPhotoPath, Toast.LENGTH_SHORT).show();
final AlertDialog dialog = builder.create();
LayoutInflater inflater = getLayoutInflater();
#SuppressLint("InflateParams") View dialogLayout = inflater.inflate(R.layout.diag_layout, null);
dialog.setView(dialogLayout);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setOnShowListener(d -> {
imgFile = new File(mCurrentPhotoPath);
if (imgFile.exists()) {
Bitmap myBitmap1 = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = dialog.findViewById(R.id.image);
myImage.setImageBitmap(myBitmap1);
}
});
dialog.show();
} else {
Toast.makeText(ImageActivity.this, "Request cancelled or something went wrong.", Toast.LENGTH_SHORT).show();
}
}
private File createImageFile() throws IOException {
// Create an image file name
#SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = ImageActivity.this.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /*directory*/
);
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
#Override
public void onPermissionsGranted(int requestCode, #NonNull List<String> perms) {
}
#Override
public void onPermissionsDenied(int requestCode, #NonNull List<String> perms) {
if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
new AppSettingsDialog.Builder(this).build().show();
}
}
}
Send different requestCode for different imageView click, And onActivityResult check the request code set image data to your imageView
capturedImageButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(photoCaptureIntent, 100);
}
});
capturedImageButton1.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(photoCaptureIntent, 101);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
switch (this.resultCode){
case 100:
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
capturedImageButton.setImageBitmap(bitmap);
break;
case 101:
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
capturedImageButton1.setImageBitmap(bitmap);
break;
default:
break;
}
}
}

Image dialog event

I have a question about my java code. I would like to open a image as a dialog and then pick the color of the image.
The colorpicker is working fine.
The dialog is working also.(Picture is opening in a popup)
The only problem is when i open the image in the dialog the colorpicker is not working anymore.
Please help?
The code!
public class MainActivity extends AppCompatActivity {
ImageView mImageView;
Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View mylayout = LayoutInflater.from(this).inflate(R.layout.activity_2,null);
final ImageView myImage = (ImageView) mylayout.findViewById(R.id.imageView1);
myImage.setDrawingCacheEnabled(true);
myImage.buildDrawingCache(true);
final Button button1 = (Button) findViewById(R.id.button1);
myImage.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE) {
try {
bitmap = myImage.getDrawingCache();
int pixel = bitmap.getPixel((int) event.getX(), (int) event.getY());
//getting RGB values
int r = Color.red(pixel);
int g = Color.green(pixel);
int b = Color.blue(pixel);
//getting Hex value
String hex = "#" + Integer.toHexString(pixel);
//set background color of view
//mColorView.setBackgroundColor(Color.rgb(r,g,b));
System.out.println("r"+r+"g"+g+"b"+b);
// Make the variable a global var easy way
} catch(Exception e){
System.out.println("FOUT JONGUH");
}
}
return true;
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.activity_2);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
});
}
}
MAIN XML:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="427dp" />
Second XML:
<?xml version="1.0" encoding="utf-8"?>
<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="match_parent">
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:srcCompat="#drawable/dirk" />
You need to declare the imageview on dialog not on layout inflater. You can do it like this;
Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.activity_2);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
final ImageView myImage = (ImageView) dialog.findViewById(R.id.imageView1); //here is the imageview
dialog.show();
myImage.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE) {
try {
bitmap = myImage.getDrawingCache();
int pixel = bitmap.getPixel((int) event.getX(), (int) event.getY());
//getting RGB values
int r = Color.red(pixel);
int g = Color.green(pixel);
int b = Color.blue(pixel);
//getting Hex value
String hex = "#" + Integer.toHexString(pixel);
//set background color of view
//mColorView.setBackgroundColor(Color.rgb(r,g,b));
System.out.println("r"+r+"g"+g+"b"+b);
// Make the variable a global var easy way
} catch(Exception e){
System.out.println("FOUT JONGUH");
}
}
return true;
}
});
then put your onTouchlistener inside the button.onClickListener
I fixed it by doing this!
// View mColorView;
TextView mResults;
Bitmap bitmap;
String dirk;
Boolean wait = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
webView = (WebView) findViewById(R.id.webview);
webView.setWebViewClient(new WebViewClient());
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
mResults = findViewById(R.id.textView4);
//mColorView = findViewById(R.id.colorView);
final Dialog dialog = new Dialog(Activity2.this);
dialog.setContentView(R.layout.popupp);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
final ImageView myImage = (ImageView) dialog.findViewById(R.id.ImageView112);
myImage.setDrawingCacheEnabled(true);
myImage.buildDrawingCache(true);
Button popupje = (Button) findViewById(R.id.popupje);
final Button gereed = (Button) findViewById(R.id.Gereed);
//image view on touch listener
gereed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
wait = true;
if(wait == true) {
myImage.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
try {
bitmap = myImage.getDrawingCache();
int pixel = bitmap.getPixel((int) event.getX(), (int) event.getY());
//getting RGB values
int r = Color.red(pixel);
int g = Color.green(pixel);
int b = Color.blue(pixel);
//set background color of view
//mColorView.setBackgroundColor(Color.rgb(r,g,b));
mResults.setText("RGB" + r + g + b);
// Make the variable a global var easy way
String srtlred = Integer.toString(r);
String srtlblue = Integer.toString(b);
String srtlgreen = Integer.toString(g);
System.out.println("http://192.168.68.158/?r" + srtlred + "g" + srtlgreen + "b" + srtlblue + "&");
webView.loadUrl("http://192.168.68.158/?r" + srtlred + "g" + srtlgreen + "b" + srtlblue + "&");
} catch (Exception e) {
//MEANS THAT THE USER IS GOING OUT OF THE IMAGEVIEW
}
}
return true;
}
});
}
//Makes the correct URL to send to the webview.
//tring srtlred = Integer.toString(red);
//String srtlblue = Integer.toString(blue);
//String srtlgreen = Integer.toString(green);
//System.out.println("http://192.168.68.158/?r"+srtlred +"g"+ srtlgreen+"b" +srtlblue+"&");
//webView.loadUrl("http://192.168.68.158/?r"+srtlred +"g"+ srtlgreen+"b" +srtlblue+"&");
}
});
}
}

Button click event not working when set X and Y coordinates

I have create simple image view and set a frame and set button is x and y coordinates before set x and y coordinates this time button click event work but set x and y coordinates not working button click event.
My Class
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ImageView viewImage;
private Button btnCapture;
private static final int RESULT_LOAD_IMAGE = 1;
private static final int REQUEST_IMAGE_CAPTURE = 2;
private Uri mCapturedImageURI;
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnCapture = (Button) findViewById(R.id.btnCapture);
btnCapture.setX(850);
btnCapture.setY(300);
btnCapture.setOnClickListener(this);
viewImage = (ImageView) findViewById(R.id.viewImage);
viewImage.setOnTouchListener(new Touch(getApplicationContext()));
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
private void activeTakePhoto() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
String fileName = "temp.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver()
.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
takePictureIntent
.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
private void activeGallery() {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_LOAD_IMAGE:
if (requestCode == RESULT_LOAD_IMAGE &&
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();
Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
viewImage.setImageBitmap(bitmap);
}
case REQUEST_IMAGE_CAPTURE:
if (requestCode == REQUEST_IMAGE_CAPTURE &&
resultCode == RESULT_OK) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor =
getContentResolver().query(mCapturedImageURI, projection, null,
null, null);
int column_index_data = cursor.getColumnIndexOrThrow(
MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String picturePath = cursor.getString(column_index_data);
cursor.close();
Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
viewImage.setImageBitmap(bitmap);
}
}
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnCapture:
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_dialog_box);
dialog.setTitle("Select Image");
Button dialogButton = (Button) dialog.findViewById(R.id.btnExit);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
Button btnChoosePath = (Button) dialog.findViewById(R.id.btnChoosePath);
btnChoosePath.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onClick(View v) {
activeGallery();
dialog.dismiss();
}
});
Button btnTakePhoto = (Button) dialog.findViewById(R.id.btnTakePhoto);
btnTakePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activeTakePhoto();
dialog.dismiss();
}
});
dialog.show();
break;
}
}
XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/btnCapture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/camera_icon" />
<RelativeLayout
android:id="#+id/FrameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/viewImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="matrix" />
</FrameLayout>
<ImageView
android:id="#+id/abc"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/aa" />
</RelativeLayout>
can you please replace onClick(View view) method with following.
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnCapture:
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_dialog_box);
dialog.setTitle("Select Image");
Button dialogButton = (Button) dialog.findViewById(R.id.btnExit);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
Button btnChoosePath = (Button) dialog.findViewById(R.id.btnChoosePath);
btnChoosePath.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onClick(View v) {
activeGallery();
dialog.dismiss();
}
});
Button btnTakePhoto = (Button) dialog.findViewById(R.id.btnTakePhoto);
btnTakePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activeTakePhoto();
dialog.dismiss();
}
});
dialog.show();
break;
}
}
Edited Answer.
Change the following thing in you MainActivity.class
btnCapture.setX(300);
btnCapture.setY(850);
and replace your xml file with the following.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="#+id/FrameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/viewImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="matrix" />
</FrameLayout>
<ImageView
android:id="#+id/abc"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/blue_squre" />
</RelativeLayout>
<ImageButton
android:id="#+id/btnCapture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher" />
And One thing in your xml you use btnCapture id for Button. and you create the object of ImageButton in your .class file. how its works for you i don't know. but i change it try it.

How to add a textview and a button, dynamically in a ListView in android?

In my app I have a ListView for listing some textviews and buttons ,also have an ImageView on the top,i have added parallax scrollview between this,now I want to add some textviews and buttons dynamically in the ListView . I have this code ;but it is not working.I am a beginner,so I could not find the actual problem. Can anybody help me out,and Please excuse my language problem?
MainActivity.java
public class MainActivity extends Activity {
private int lastTop = 0;
//ImageView image;
ListView listView;
private static int RESULT_LOAD_IMAGE = 1;
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
ArrayAdapter adapter;
ArrayList<String> items = new ArrayList<>();
public void parallax(final View v) {
final Rect r = new Rect();
v.getLocalVisibleRect(r);
if (lastTop != r.top) {
lastTop = r.top;
v.post(new Runnable() {
#Override
public void run() {
v.setY((float) (r.top / 2.0));
}
});
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
//Dynamic textvieww
final LinearLayout lm = (LinearLayout) findViewById(R.id.linear);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
AbsListView.LayoutParams.WRAP_CONTENT, AbsListView.LayoutParams.WRAP_CONTENT);
//Create four
for(int j=0;j<=4;j++)
{
// Create LinearLayout
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
// Create TextView
TextView product = new TextView(this);
product.setText(" Product"+j+" ");
ll.addView(product);
// Create TextView
TextView price = new TextView(this);
price.setText(" $"+j+" ");
ll.addView(price);
// Create Button
final Button btn = new Button(this);
// Give button an ID
btn.setId(j+1);
btn.setText("Add To Cart");
// set the layoutParams on the button
btn.setLayoutParams(params);
final int index = j;
// Set click listener for button
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.i("TAG", "index :" + index);
Toast.makeText(getApplicationContext(),
"Clicked Button Index :" + index,
Toast.LENGTH_LONG).show();
}
});
//Add button to LinearLayout
ll.addView(btn);
//Add button to LinearLayout defined in XML
lm.addView(ll);
}
//EOF Dynamic
View view = getLayoutInflater().inflate(R.layout.header, null, false);
//Image view block
Button buttonLoadImage = (Button) view.findViewById(R.id.buttonLoadPicture);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
this.imageView = (ImageView)view.findViewById(R.id.imgView);
Button photoButton = (Button) view.findViewById(R.id.button2);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
//imageview block end
// image = (ImageView) view.findViewById(R.id.image);
listView.addHeaderView(view);
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
parallax(imageView);
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
parallax(imageView);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && 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.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
}
activity_main.xml
<FrameLayout xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="in.zoid.parallaxtutorial.MainActivity">
<LinearLayout
android:id="#+id/linear"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ListView
android:id="#+id/listView"
android:layout_height="wrap_content"
android:layout_width="match_parent" />
</LinearLayout>
</FrameLayout>
header.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linear"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView android:id="#+id/imgView"
android:layout_width="wrap_content"
android:layout_height="200dip"
android:scaleType="centerCrop" ></ImageView>
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:color/black" >
<Button android:id="#+id/buttonLoadPicture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:text="Load Picture"
android:layout_gravity="center"></Button>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Take Picture"
android:layout_alignParentRight="true"/>
</RelativeLayout>
</LinearLayout>
See this Example it may useful to add data dynamically in list view in android

Multiple TouchImageView resets other when one's setImageDrawable is called

I am trying to use multiple TouchImageView in one View. Then on single click in TouchImageView picking image from gallery to show in TouchImageView. But the problem is when I set a new Image from gallery in one TouchImageView the other gets also reset means the last zooming is still right of that TouchImageView but the last position of the image inside that gets repositioned.
Here is my code:
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<com.example.imagedragpinchtest.TouchImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:id="#+id/TIV1"
android:src="#drawable/ic_launcher"
android:background="#drawable/dashline"
android:layerType="software"
/>
<com.example.imagedragpinchtest.TouchImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:id="#+id/TIV2"
android:src="#drawable/ic_launcher"
android:background="#drawable/dashline"
android:layerType="software"/>
</LinearLayout>
MainActivity.java
package com.example.imagedragpinchtest;
public class MainActivity extends Activity {
TouchImageView tiv1,tiv2;
int selected = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tiv1 = (TouchImageView) findViewById(R.id.TIV1);
tiv2 = (TouchImageView) findViewById(R.id.TIV2);
tiv1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
selected = 1;
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, selected);
}
});
tiv2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
selected = 2;
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, selected);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
String imgPath = getPathFromUri(data.getData());
Log.e("new", imgPath);
if(selected == 1)
tiv1.setImageDrawable(new BitmapDrawable(getResources(), imgPath));
if(selected == 2)
tiv2.setImageDrawable(new BitmapDrawable(getResources(), imgPath));
}
}
public String getPathFromUri(Uri uri) {
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
return picturePath;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
The library TouchImageView.java
I can't figure out where the problem is, I have also tried by comment out the onSaveInstanceState() and onRestoreInstanceState() of the TouchImageView class. But that also don't solve the problem. Some help will be really appreciable. Thanks in advance.....

Categories