call method with multiple parameters in onClick() of a button - android

I am new to Android and I am trying to Build a gallery app with Edit Activity. I have attached the screenshot of edit screen of my app. There is an ImageView, a SeekBar and 4 ImageButtons. The ImageButtons implements 4 edit functionality-Brightness,saturation and etc.. I have all methods for effects. All I want to know is when I click the imageButton(may be brightness), and drag the seekbar, the brightness should increase and similarly, when i click Contrast ImageButton and drag the seekbar, Contrast of Image should Increase. How can I implement it. Could Someone Please help me with it.. I tried using setOnTouchListener() for ImageButtons but that dint work, as it accepts only view as parameter and not Bitmap. Please help me.Thanks in Advance
Below is my Edit Activity
public class EditActivity extends Activity
{
private Bitmap bitmap;
private ImageView image;
private ImageButton bb,sab,shb,cb;
private BitmapDrawable drawable;
private SeekBar seekBar;
#Override
public void onCreate( Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.filters);
// Get intent data
Intent i = getIntent();
// Selected image id
final int position = i.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
image = (ImageView) findViewById(R.id.imageView);
image.setImageResource(imageAdapter.ids[position]);
bb = (ImageButton) findViewById(R.id.brightButton);
drawable = (BitmapDrawable) image.getDrawable();
bitmap = drawable.getBitmap();
bb.setImageBitmap(bitmap);
sab=(ImageButton)findViewById(R.id.saturationButton);
drawable = (BitmapDrawable) image.getDrawable();
bitmap = drawable.getBitmap();
sab.setImageBitmap(bitmap);
cb=(ImageButton) findViewById(R.id.contrastButton);
drawable = (BitmapDrawable) image.getDrawable();
bitmap = drawable.getBitmap();
cb.setImageBitmap(bitmap);
shb=(ImageButton) findViewById(R.id.sharpButton);
drawable = (BitmapDrawable) image.getDrawable();
bitmap = drawable.getBitmap();
shb.setImageBitmap(bitmap);
SeekBar seekBar=(SeekBar)findViewById(R.id.seekBar);
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
int brightness;
#Override
public void onStopTrackingTouch(SeekBar arg0) {
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
}
#Override
public void onProgressChanged(SeekBar arg0, final int progress, boolean arg2)
{
brightness = progress;
Bitmap bBitMap = brightClicked(bitmap,progress);
image.setImageBitmap(bBitMap);
Bitmap saBitMap = sharpClicked(bitmap,progress);
image.setImageBitmap(saBitMap);
Bitmap cBitMap = saturationClicked(bitmap,progress);
image.setImageBitmap(cBitMap);
Bitmap shBitMap = contrastClicked(bitmap,progress);
image.setImageBitmap(shBitMap);
}
});
}
public Bitmap brightClicked(Bitmap bbitmap,int value)
{
Bitmap bmOut= Bitmap.createBitmap(bbitmap.getWidth(), bbitmap.getHeight(),bbitmap.getConfig());
int A, R, G, B;
int pixel;
for(int i=0; i<bbitmap.getWidth(); i++){
for(int j=0; j<bbitmap.getHeight(); j++)
{
pixel = bbitmap.getPixel(i, j);
A = Color.alpha(pixel);
R = Color.red(pixel);
G = Color.green(pixel);
B = Color.blue(pixel);
R += value;
if (R > 255)
{
R = 255;
} else if (R < 0)
{
R = 0;
}
G += value;
if (G > 255)
{
G = 255;
} else if (G < 0)
{
G = 0;
}
B += value;
if (B > 255)
{
B = 255;
} else if (B < 0)
{
B = 0;
}
bmOut.setPixel(i, j, Color.argb(A, R, G, B));
}
}
return bmOut;
}// and other methods of effects like sharpness,contrast..
Below is Screenshot of EditImage

I would begin with defining state so that the SeekBar can quickly determine which attribute it should be modifying (contrast, brightness, sharpness, saturation). Throw these into an enum class (Google recommends avoiding enums in Android) if you like or define them within the class itself as ints. For example:
public class EditActivity extends Activity {
private int currentState;
private static final int SATURATE = 0;
private static final int CONTRAST = 1;
....
}
Now you can just have the state be updated based on the button clicked:
bb = (ImageButton) findViewById(R.id.brightButton);
bb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentState = BRIGHTNESS;
}
}
Then use a switch-case statement to quickly determine the state of the Activity and adjust the image accordingly through your image methods.
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
#Override
public void onProgressChanged(SeekBar arg0, final int progress, boolean arg2)
{
brightness = progress;
switch (currentState) {
case (SATURATE) :
image.setImageBitmap(saturationClicked(bitmap,progress));
break;
case (CONTRAST) :
image.setImageBitmap(contrastClicked(bitmap,progress));
break;
It looks like your current implementation would run all your filters on the image any time the seek bar is moved, which I imagine would cause horrible performance. A switch case would just help you avoid that.

Related

How to blur the background image of the main layout in android?

I just want to make the background image to look blur(like defocus),I used alpha but it was not only setting alpha to my background image but also to the whole content...Is there any way that I can set blur effect only to my background image!!!..
need help thanks in advance!!..
Please use below tutorial for blur background
NavigationDrawer :
https://github.com/charbgr/BlurNavigationDrawer
Fragment:
https://github.com/tvbarthel/BlurDialogFragment
Image : If you want to blur an image in layout :
https://github.com/kikoso/android-stackblur
Layout:
https://github.com/PomepuyN/BlurEffectForAndroidDesign
public class MainActivity extends Activity {
private static final String BLURRED_IMG_PATH = "blurred_image.png";
private static final int TOP_HEIGHT = 700;
private ListView mList;
private ImageView mBlurredImage;
private View headerView;
private ImageView mNormalImage;
private ScrollableImageView mBlurredImageHeader;
private Switch mSwitch;
private float alpha;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_main);
// Get the screen width
final int screenWidth = ImageUtils.getScreenWidth(this);
// Find the view
mBlurredImage = (ImageView) findViewById(R.id.blurred_image);
mNormalImage = (ImageView) findViewById(R.id.normal_image);
mBlurredImageHeader = (ScrollableImageView) findViewById(R.id.blurred_image_header);
mSwitch = (Switch) findViewById(R.id.background_switch);
mList = (ListView) findViewById(R.id.list);
// prepare the header ScrollableImageView
mBlurredImageHeader.setScreenWidth(screenWidth);
// Action for the switch
mSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mBlurredImage.setAlpha(alpha);
} else {
mBlurredImage.setAlpha(0f);
}
}
});
// Try to find the blurred image
final File blurredImage = new File(getFilesDir() + BLURRED_IMG_PATH);
if (!blurredImage.exists()) {
// launch the progressbar in ActionBar
setProgressBarIndeterminateVisibility(true);
new Thread(new Runnable() {
#Override
public void run() {
// No image found => let's generate it!
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.image, options);
Bitmap newImg = Blur.fastblur(MainActivity.this, image, 12);
ImageUtils.storeImage(newImg, blurredImage);
runOnUiThread(new Runnable() {
#Override
public void run() {
updateView(screenWidth);
// And finally stop the progressbar
setProgressBarIndeterminateVisibility(false);
}
});
}
}).start();
} else {
// The image has been found. Let's update the view
updateView(screenWidth);
}
String[] strings = getResources().getStringArray(R.array.list_content);
// Prepare the header view for our list
headerView = new View(this);
headerView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, TOP_HEIGHT));
mList.addHeaderView(headerView);
mList.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, strings));
mList.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
/**
* Listen to the list scroll. This is where magic happens ;)
*/
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// Calculate the ratio between the scroll amount and the list
// header weight to determinate the top picture alpha
alpha = (float) -headerView.getTop() / (float) TOP_HEIGHT;
// Apply a ceil
if (alpha > 1) {
alpha = 1;
}
// Apply on the ImageView if needed
if (mSwitch.isChecked()) {
mBlurredImage.setAlpha(alpha);
}
// Parallax effect : we apply half the scroll amount to our
// three views
mBlurredImage.setTop(headerView.getTop() / 2);
mNormalImage.setTop(headerView.getTop() / 2);
mBlurredImageHeader.handleScroll(headerView.getTop() / 2);
}
});
}
private void updateView(final int screenWidth) {
Bitmap bmpBlurred = BitmapFactory.decodeFile(getFilesDir() + BLURRED_IMG_PATH);
bmpBlurred = Bitmap.createScaledBitmap(bmpBlurred, screenWidth, (int) (bmpBlurred.getHeight()
* ((float) screenWidth) / (float) bmpBlurred.getWidth()), false);
mBlurredImage.setImageBitmap(bmpBlurred);
mBlurredImageHeader.setoriginalImage(bmpBlurred);
}
}
Kotlin code, use view effect Library :
1- Add library in build.gradle:
implementation 'com.github.mirrajabi:view-effects:e355a1bac4'
2- Blure the background of root view or view, here Constraint Layout blured by 20%
ViewFilter.getInstance(this)
.setRenderer( BlurRenderer(20))
.applyFilterOnView( root_constraintLayout,
root_constraintLayout )
my github repository for blur background : link

View setBackgroundColor not working android

I have a problem with setting background color of a view (Note: all elements are View)
public class MainActivity extends ActionBarActivity {
final Context context = this;
//Original Colors (Hardcodeded for nice looks)
int r1c = Color.parseColor("#ff00eeff");
int r2c = Color.parseColor("#ff21ff2e");
//Final Colors Random
int r1f = randomColor();
int r2f = randomColor();
//Get int for progress
int progress = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final View r1 = (View) findViewById(R.id.r1);
final View r2 = (View) findViewById(R.id.r2);
final SeekBar bar = (SeekBar) findViewById(R.id.seekBar);
bar.setProgress(0);
bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progress = bar.getProgress();
updateColors(r1,r1c,r1f);
updateColors(r2,r2c,r2f);
//updateColors(r1,r1c,r1f); Grey in this case TODO automatic
}
});
}
public void updateColors(View v, int ogcolor, int fcolor) {
ArgbEvaluator getColorAtPos = new ArgbEvaluator();
float percent = (float) progress / 100; //Does this return float expected between 0.0 and 1.0 ???? Im new to java so not sure
v.setBackgroundColor((Integer) getColorAtPos.evaluate(percent, ogcolor, fcolor));
v.invalidate();
}
int randomColor() {
Random rand = new Random();
int r = (int) rand.nextInt(255);
int g = (int) rand.nextInt(255);
int b = (int) rand.nextInt(255);
int color = Color.argb(255,r, g, b);
return color;
}
}
I have described most in comments in code, but once more, when I move seekBar, onProgressChanged is called successfully, also updatecolors is called, yet I can't see the color changing on activity.
ok got it , GetProgress() was not working as expected , so value of process was always 0 , (int progress was defined at start of onCreate and it is also in args of onProgressChanged so there was conflict ,but i wonder why AS did not warn me about same var name twice

Move an Image continously in Random position within the display in android

Can anyone help me to do this.
I am trying to build an android app but stuck in between.
i have use the following code to move a image.
iv is ImageView object
moveImage = new TranslateAnimation( 0, xDest, 0, -yDest);
moveImage.setDuration(1000);
moveImage.setFillAfter( true );
iv.startAnimation(moveImage);
code:
public class gameLogic extends Activity
{
ImageView image;
TranslateAnimation moveImage;
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.game_logic);
imageMoveRandom(imageList(image,0));
}
ImageView imageList(ImageView v,int i)
{
v = (ImageView) findViewById(R.id.rabbit);
int imgId;
int j = i;
TypedArray imgs = getResources().obtainTypedArray(R.array.random_imgs);
//get resourceid by index
imgId = imgs.getResourceId(j, 0);
// or set you ImageView's resource to the id
v.setBackgroundResource(imgId);
return v;
}
void imageMoveRandom(ImageView iv)throws NotFoundException
{
DisplayMetrics dm = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics( dm );
int xDest = dm.widthPixels/2;
int yDest = dm.heightPixels/2;
// Toast.makeText(gameLogic.this, dm.widthPixels, Toast.LENGTH_SHORT).show();
// Toast.makeText(this, dm.heightPixels, 2000).show();
moveImage = new TranslateAnimation( 0, xDest, 0, -yDest);
moveImage.setDuration(1000);
moveImage.setFillAfter( true );
iv.startAnimation(moveImage);
//moveImage.reset();
}
}
Above is not full code..but part which may be helpful for references.
But i want to continuously move the image in random place but within the android display.
Can any one suggest the solution.
Thanks in Advance :)
class BitmapView extends View
{
changingX=10;
changingY=10;
public BitmapView(Context context) {
super(context);
}
#Override
public void onDraw(Canvas canvas) {
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.yourImageName);
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(bmp, changingX,changingY, null);
changingX=changingX+5;
changingY=changingY+10;
invalidate();
}
}
Try this

Android seekbar with custom thumb having dynamic text inside it

I want to create android custom SeekBar having thumb with text inside it to show current seek position.
Here is my code:
SeekBar sb;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_seek_bar_activity);
sb = (SeekBar)findViewById(R.id.slider);
sb.setMax(100);
sb.setProgress(10);
BitmapDrawable bd = writeOnDrawable(R.drawable.star2, Double.toString(50));
sb.setThumb(bd);
sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
{
int pos = sb.getProgress();
double star = pos/(20.0);
TextView tv = (TextView)findViewById(R.id.percent);
tv.setText(Double.toString(star)+"%");
BitmapDrawable bd = writeOnDrawable(R.drawable.star2, Double.toString(star));
bd.setBounds(new Rect(0,0,
bd.getIntrinsicWidth(),
bd.getIntrinsicHeight()
));
seekBar.setThumb(bd);
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
});
}
public BitmapDrawable writeOnDrawable(int drawableId, String text){
Bitmap bm = BitmapFactory.decodeResource(getResources(), drawableId).copy(Bitmap.Config.ARGB_8888, true);
Paint paint = new Paint();
paint.setStyle(Style.FILL);
paint.setColor(Color.BLACK);
paint.setTextSize(10);
Canvas canvas = new Canvas(bm);
canvas.drawText(text, 0, bm.getHeight()/2, paint);
return new BitmapDrawable(bm);
}
but when I move thumb it goes to the beginning of the seek bar.
Does anyone have solution to move custom thumb with seekbar position?
I use SeekBar to display a timer countdown in my app. Inside the timer thumb I show the current SeekBar progress number using the below code:
SeekBar timerBar = (SeekBar) findViewById(R.id.seekBarTimer);
if (timerBar != null) {
timerBar.setMax((int) (Settings.countdownSeconds + 1));
timerBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
}
#Override
public void onProgressChanged(SeekBar timerBar, int arg1, boolean arg2) {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.seek_thumb);
Bitmap bmp = bitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas c = new Canvas(bmp);
String text = Integer.toString(timerBar.getProgress());
Paint p = new Paint();
p.setTypeface(Typeface.DEFAULT_BOLD);
p.setTextSize(14);
p.setColor(0xFFFFFFFF);
int width = (int) p.measureText(text);
int yPos = (int) ((c.getHeight() / 2) - ((p.descent() + p.ascent()) / 2));
c.drawText(text, (bmp.getWidth()-width)/2, yPos, p);
timerBar.setThumb(new BitmapDrawable(getResources(), bmp));
}
});
timerBar.setProgress(0);
}
The R.drawable.seek_thumb drawable is my thumb drawable.
I got solution now, in setBound() method I was passing top left as 0, that's why it is showing seek bar at beginning. After doing following change I got it works.
Call setThumbPos() method in onProgressChanged() event
public void setThumbPosition(SeekBar seekBar){
int max = seekBar.getMax();
int available = seekBar.getWidth() - seekBar.getPaddingLeft() - seekBar.getPaddingRight();
float scale = max > 0 ? (float) seekBar.getProgress() / (float) max : 0;
//scale = 1;
int pos = sb.getProgress();
double star = pos/(20.0);
BitmapDrawable bd = writeOnDrawable(R.drawable.star2, Double.toString(star));
int thumbWidth = bd.getIntrinsicWidth();
int thumbHeight = bd.getIntrinsicHeight();
//available -= thumbWidth;
int thumbPos = (int) (scale * available);
if(thumbPos <= 0+thumbWidth){
thumbPos += (thumbWidth/2);
}else if(thumbPos >= seekBar.getWidth()-thumbWidth){
thumbPos -= (thumbWidth/2);
}
bd.setBounds(new Rect(thumbPos,0,
thumbPos+bd.getIntrinsicWidth(),
bd.getIntrinsicHeight()
));
seekBar.setThumb(bd);
TextView tv = (TextView)findViewById(R.id.percent);
tv.setText(Double.toString(star)+"%");
}
I ended up using this simple solution. Its probably not as high-performance as say a proper custom SeekBar, however its really easy to plug into an existing layout, and use any label or other view on top of the SeekBar thumb.
protected void positionThumbLabel(SeekBar seekBar, TextView label)
{
Rect tr = seekBar.getThumb().getBounds();
label.setWidth(tr.width());
label.setX(tr.left + seekBar.getPaddingLeft());
}
With some minor changes you can position an overlay relative to the center of the thumb:
protected void positionThumbOverlayCenter(SeekBar seekBar, View overlay)
{
Rect tr = seekBar.getThumb().getBounds();
overlay.setX(tr.centerX() - (overlay.getWidth() * 0.5f) + seekBar.getPaddingLeft());
}
Pick a solution that match your situation here: http://www.helptouser.com/code/10722746-add-dynamic-text-over-android-seekbar-thumb.html

Programmatically set random number in images

I have 4 speech bubble, which of 2 have question in white speech bubble and another 2 blue bubble have answers . I have done showing random image but how to generate question and answers randomly,i have confusion in that. I did not understand how to programmatically set text in image( speech bubble in this case). These are images cleaging more of my problem.!
next time question display following types.
i have done following code:
public class TestingActivity extends Activity {
ImageView i1, i2, i3, i4;
int TwoArray[][] = new int[6][5];
static int i;
static int j;
static int a = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setupVeiw();
setImages();
}
// Shuffle here
private void setupVeiw() {
i1 = (ImageView) findViewById(R.id.imageView1);
i2 = (ImageView) findViewById(R.id.imageView2);
i3 = (ImageView) findViewById(R.id.imageView3);
i4 = (ImageView) findViewById(R.id.imageView4);
}
public int getImage(int val)
{
if (val == 0)
{
// How to set programmatically **questions** numbers in spechh bubble
return R.drawable.speech_white;
}
else
{
// How to set programmatically **answers** numbers in spechh bubble
return R.drawable.speech_blue;
}
}
public void setImages()
{
try {
int numArray[] = { 0, 0,1, 1 };
shuffleList(numArray);
for (i = 0; i < numArray.length - 1; i++)
{
switch (i)
{
case 0:
i1.setImageResource(getImage(numArray[i]));
break;
case 1:
i2.setImageResource(getImage(numArray[i]));
break;
case 2:
i3.setImageResource(getImage(numArray[i]));
break;
case 3:
i4.setImageResource(getImage(numArray[i]));
break;
default:
break;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
I am waiting for your good advice.
Thank you advance.
Would be nice if you would use TextView instead, you can still set a background image in text view.
First, to generate a question, you can create a class named Question with the following properties.
public static int ADDITION = 1; // for example's sake
double x, y; // your variables
int operation; // operation
public Question(double x, double y, int operation) {
this.x = x;
this.y = y;
this.operation = operation
}
public double returnAnswer() {
double answer = 0;
if(operation == Question.ADDITION) {
answer = x + y;
}
return answer;
}
And then you can generate questions
Question firstQuestion = new Question(Math.random(), Math.random(), Question.ADDITION);
Instead of using ImageViews to display the question, you can use TextViews. Use the setText() method to display the question and the setBackground() method to change the background image.

Categories

Resources