Replacing Bitmap with Drawable in Drag and Drop Example - java

I'm attempting to modify a drag and drop gridView example to use a specific drawable instead of the bitmap used in the example.
I believe I'll need to edit the line: Bitmap bmp = Bitmap.createBitmap(150, 150, Bitmap.Config.RGB_565);
and change it to something such as Bitmap bmp = R.drawable.sqwhite; but I don't think that's exactly what I'm looking for.
Any suggestions?
Source:
public class DraggableGridViewSampleActivity extends Activity {
static Random random = new Random();
static String[] words = "the of and a to in is be that was he for it with as his I on have at by not they this had are but from or she an which you one we all were her would there their will when who him been has more if no out do so can what up said about other into than its time only could new them man some these then two first may any like now my such make over our even most me state after also made many did must before back see through way where get much go well your know should down work year because come people just say each those take day good how long Mr own too little use US very great still men here life both between old under last never place same another think house while high right might came off find states since used give against three himself look few general hand school part small American home during number again Mrs around thought went without however govern don't does got public United point end become head once course fact upon need system set every war put form water took".split(" ");
DraggableGridView dgv;
Button button1, button2;
ArrayList<String> poem = new ArrayList<String>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dgv = ((DraggableGridView)findViewById(R.id.vgv));
button1 = ((Button)findViewById(R.id.button1));
button2 = ((Button)findViewById(R.id.button2));
setListeners();
}
private void setListeners()
{
dgv.setOnRearrangeListener(new OnRearrangeListener() {
public void onRearrange(int oldIndex, int newIndex) {
String word = poem.remove(oldIndex);
if (oldIndex < newIndex)
poem.add(newIndex, word);
else
poem.add(newIndex, word);
}
});
dgv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
dgv.removeViewAt(arg2);
poem.remove(arg2);
}
});
button1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
String word = words[random.nextInt(words.length)];
ImageView view = new ImageView(DraggableGridViewSampleActivity.this);
view.setImageBitmap(getThumb(word));
dgv.addView(view);
poem.add(word);
}
});
button2.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
String finishedPoem = "";
for (String s : poem)
finishedPoem += s + " ";
new AlertDialog.Builder(DraggableGridViewSampleActivity.this)
.setTitle("Here's your poem!")
.setMessage(finishedPoem).show();
}
});
}
private Bitmap getThumb(String s)
{
Bitmap bmp = Bitmap.createBitmap(150, 150, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bmp);
Paint paint = new Paint();
paint.setColor(Color.rgb(random.nextInt(128), random.nextInt(128), random.nextInt(128)));
paint.setTextSize(24);
paint.setFlags(Paint.ANTI_ALIAS_FLAG);
canvas.drawRect(new Rect(0, 0, 150, 150), paint);
paint.setColor(Color.WHITE);
paint.setTextAlign(Paint.Align.CENTER);
canvas.drawText(s, 75, 75, paint);
return bmp;
}
}
Full Source:
https://github.com/thquinn/DraggableGridView

Related

Is there a way to restart marquee/scrolling when the last letter of the text becomes visible?

I want a text inside a textbox to scroll to end and then restart.
Using marquee scrolls the whole text until the first letter reaches the "start point", but I want the text only to scroll until the last letter of the text becomes visible, then pause and the text should jump to start and start scrolling again.
Is there a way to do this. I have search but I can't find something that works for me.
Thanks,
Sebi
I am not aware of any way to configure a TextView to take on the marquee behavior that you are seeking. The Stack Overflow Q/A I referred you to in the comments does translate the entire TextView. I think that this will work as a marquee if you set the TextView within a ViewGroup such that the TextView is clipped. You can also do you own clipping. You would have to try this to see if it would work. If this does work, it may be sufficient for your needs, but you may be missing the fading edge and maybe some other characteristics of true marquee scrolling. Also, some other characteristics of the TextView such as shadows, borders and backgrounds might not look right.
The contents of the TextView is animated by the TextView code itself through canvas translation for marquee scrolling. See here.
if (isMarqueeFadeEnabled()) {
if (!mSingleLine && getLineCount() == 1 && canMarquee()
&& (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) != Gravity.LEFT) {
final int width = mRight - mLeft;
final int padding = getCompoundPaddingLeft() + getCompoundPaddingRight();
final float dx = mLayout.getLineRight(0) - (width - padding);
canvas.translate(layout.getParagraphDirection(0) * dx, 0.0f);
}
if (mMarquee != null && mMarquee.isRunning()) {
final float dx = -mMarquee.getScroll();
canvas.translate(layout.getParagraphDirection(0) * dx, 0.0f);
}
}
You can also consider writing a custom TextView and doing your own text scrolling. You can look to the TextView code itself for some tips on how you might do it. I think writing your own TextView would have better results. (IMO)
I have rewrite the Code from the GitHub Project here (which was posted in the comment from Cheticamp) to java and shorten it to my needs. Now it starts the animation infinite.
Here the java code:
MarqueeTextView.java:
public class MarqueeTextView extends androidx.appcompat.widget.AppCompatTextView {
private final Scroller mScroller;
private int mDelay;
private int mDuration;
private final Handler mHandler = new Handler();
private final Runnable mAnimateRunnable = new Runnable() {
#Override
public void run() {
//check if Animation is needed otherwise check next cycle (if text has changed for example)
if (getTextViewWidthWithPadding() < getTextWidth()) {
mScroller.startScroll(getStartX(), 0, 0, 0, 0);
invalidate();
int direction = getLayout().getParagraphDirection(0);
mScroller.startScroll(getStartX(), 0, (getTextWidth() - getTextViewWidthWithPadding()) * direction, 0, mDuration);
}
mHandler.postDelayed(mAnimateRunnable, mDelay);
}
};
public MarqueeTextView(Context context) {
this(context, null);
}
public MarqueeTextView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
mScroller = new Scroller(context, new LinearInterpolator());
setScroller(mScroller);
}
private int getTextWidth() {
String text = getText().toString();
TextPaint paint = getPaint();
Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
return bounds.width();
}
private int getTextViewWidthWithPadding() {
return getWidth() - (getPaddingStart() + getPaddingEnd());
}
private int getStartX() {
boolean isRtl = getLayoutDirection() == LAYOUT_DIRECTION_RTL;
int lineRight = (int) getLayout().getLineRight(0);
if (isRtl) {
return lineRight - getTextViewWidthWithPadding();
} else {
return 0;
}
}
public void startAnimation(int delay, int duration) {
mDelay = delay;
mDuration = duration;
mHandler.postDelayed(mAnimateRunnable, delay);
}
}
activity_main.xml:
<MarqueeTextView
android:id="#+id/name"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:ellipsize="none"
android:singleLine="true"
android:text="1. Simple text that shows how to use custom marquee"
/>
MainActivty.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((MarqueeTextView)findViewById(R.id.name)).startAnimation(3000, 2000);
}

Set color seekbar

I'm creating a small paint android app using android studio java. I create in the menu an icon for changing the color of the drawing. Once the user click on it a new AlertDialog should appear showing 4 seekbars for ARGB colors. I ended with this code but I still don't know why it's not working. Can someone please help me?
private Drawing draws;
private SeekBar alphaSeekBar;
private SeekBar redSeekBar;
private SeekBar greenSeekBar;
private SeekBar blueSeekBar;
private void showColorDialog(){
currentAlertDialog = new AlertDialog.Builder(this);
View view = getLayoutInflater().inflate(R.layout.color_dialog, null);
alphaSeekBar = view.findViewById(R.id.alphaSeekBar);
redSeekBar = view.findViewById(R.id.redSeekBar);
greenSeekBar = view.findViewById(R.id.greenSeekBar);
blueSeekBar = view.findViewById(R.id.blueSeekBar);
colorView = view.findViewById(R.id.colorView);
alphaSeekBar.setOnSeekBarChangeListener(colorSeekBarChanged);
redSeekBar.setOnSeekBarChangeListener(colorSeekBarChanged);
greenSeekBar.setOnSeekBarChangeListener(colorSeekBarChanged);
blueSeekBar.setOnSeekBarChangeListener(colorSeekBarChanged);
int color = draws.getDrawingColor();
alphaSeekBar.setProgress(Color.alpha(color));
redSeekBar.setProgress(Color.red(color));
greenSeekBar.setProgress(Color.green(color));
blueSeekBar.setProgress(Color.blue(color));
Button setColorButton = view.findViewById(R.id.setColorButton);
setColorButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pikassoView.setDrawingColor(Color.argb(
alphaSeekBar.getProgress(),
redSeekBar.getProgress(),
greenSeekBar.getProgress(),
blueSeekBar.getProgress()
));
colorDialog.dismiss();
}
});
currentAlertDialog.setView(view);
currentAlertDialog.setTitle("Choose color");
colorDialog = currentAlertDialog.create();
colorDialog.show();
} private SeekBar.OnSeekBarChangeListener colorSeekBarChanged = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
draws.setBackgroundColor(Color.argb(
alphaSeekBar.getProgress(),
redSeekBar.getProgress(),
greenSeekBar.getProgress(),
blueSeekBar.getProgress()
));
colorView.setBackgroundColor(Color.argb(
alphaSeekBar.getProgress(),
redSeekBar.getProgress(),
greenSeekBar.getProgress(),
blueSeekBar.getProgress()
));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
};
First, this alphaSeekBar.setProgress(Color.alpha(color)); is wrong. setProgress is meant for setting int value to show how much progress seekbar has.
If your seekBar Max is set to 100 (alphaSeekBar.setMax(100);) then this alphaSeekBar.setProgress(50); means seekBar is progressed half way.
Second, to set colors use this:
alphaSeekBar.setProgressTintList(Color.alpha(color));
alphaSeekBar.setThumbTintList(Color.alpha(color));
Or, use this:
alphaSeekBar.getProgressDrawable().setColorFilter(Color.alpha(color), PorterDuff.Mode.MULTIPLY);
try different tint modes in place of PorterDuff.Mode.MULTIPLY to get your desired result
good luck
EDIT:
For setting a custom view to Alert Dialog
currentAlertDialog = new AlertDialog.Builder(this);
// ...Irrelevant code for customizing the buttons and title
View view = getLayoutInflater().inflate(R.layout.color_dialog, null);
currentAlertDialog.setView(view);
then you can get those seekbar references like below:
alphaSeekBar = currentAlertDialog.findViewById(R.id.alphaSeekBar);
redSeekBar = currentAlertDialog.findViewById(R.id.redSeekBar);
greenSeekBar = currentAlertDialog.findViewById(R.id.greenSeekBar);
blueSeekBar = currentAlertDialog.findViewById(R.id.blueSeekBar);
colorView = currentAlertDialog.findViewById(R.id.colorView);

How do I randomize images in android studio? The code I wrote isn't working

I want to randomize the the back images that will be brought from a database(code still not added), but the code I wrote isn't working. I have originally just added the flip function. I searched up how to randomize images and tried to follow the code given. Sadly its not working for me.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get references to the imageView objects
imgUpperLeft = (ImageView) findViewById(R.id.imgUpperLeft);
imgUpperRight = (ImageView) findViewById(R.id.imageView2);
imgLowerLeft = (ImageView) findViewById(R.id.imageView3);
imgLowerRight = (ImageView) findViewById(R.id.imageView4);
// Setting the initial image (First face of cards)
imgUpperLeft.setImageResource(R.drawable.img_waterfall);
imgUpperRight.setImageResource(R.drawable.img_waterfall);
imgLowerLeft.setImageResource(R.drawable.img_waterfall);
imgLowerRight.setImageResource(R.drawable.img_waterfall);
imgUpperLeft.setVisibility(View.VISIBLE);
imgUpperRight.setVisibility(View.VISIBLE);
imgLowerLeft.setVisibility(View.VISIBLE);
imgLowerRight.setVisibility(View.VISIBLE);
}
ImageView imgView = new ImageView(this);
Random rand = new Random();
int rndInt = rand.nextInt(4) + 1; // n = the number of images, that start at idx 1
String imgName = "img" + rndInt;
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
// Shows the second face of the cards
public void showUpperLeftImage(View v){
imgView.setImageResource(id);
}
public void showUpperRightImage(View v){
imgView.setImageResource(id);
}
public void showLowerLeftImage(View v){
imgView.setImageResource(id);
}
public void showLowerRightImage(View v){
imgView.setImageResource(id);
}
Two things in your code stand out to me:
ImageView imgView = new ImageView(this);
This ImageView is not part of the view hierarchy, meaning it is not on screen. Was it ever meant to be on screen? If not, then I don't think you need this.
public void showUpperLeftImage(View v){
imgView.setImageResource(id);
}
You have four methods like this one that change the image of the view that is not on screen. Judging by their method names, I think you want to change the image of the four ImageViews you found earlier with findViewById().
I think you want to do this:
public void showUpperLeftImage(int id) {
imgUpperLeft.setImageResource(id);
}
public void showUpperRightImage(int id) {
imgUpperRight.setImageResource(id);
}
public void showLowerLeftImage(int id) {
imgLowerLeft.setImageResource(id);
}
public void showLowerRightImage(int id) {
imgLowerRight.setImageResource(id);
}

How to rotate image in imageview on button click each time?

This is java code.I am getting image from image gallery.I have one Button and one ImageView. It is rotating only one time.When I again click button it is not rotating image.
public class EditActivity extends ActionBarActivity
{
private Button rotate;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
rotate=(Button)findViewById(R.id.btn_rotate1);
imageView = (ImageView) findViewById(R.id.selectedImage);
String path = getIntent().getExtras().getString("path");
final Bitmap bitmap = BitmapFactory.decodeFile(path);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, 510, 500,
false));
rotate.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
imageView.setRotation(90);
}
});
}
Change your onClick() method to
#Override
public void onClick(View v)
{
imageView.setRotation(imageView.getRotation() + 90);
}
Notice, what the docs say
Sets the degrees that the view is rotated around the pivot point. Increasing values result in clockwise rotation.
I'd like to update my answer to show how to use RotateAnimation to achieve the same effect in case you're also targeting Android devices running Gingerbread (v10) or below.
private int mCurrRotation = 0; // takes the place of getRotation()
Introduce an instance field to track the rotation degrees as above and use it as:
mCurrRotation %= 360;
float fromRotation = mCurrRotation;
float toRotation = mCurrRotation += 90;
final RotateAnimation rotateAnim = new RotateAnimation(
fromRotation, toRotation, imageview.getWidth()/2, imageView.getHeight()/2);
rotateAnim.setDuration(1000); // Use 0 ms to rotate instantly
rotateAnim.setFillAfter(true); // Must be true or the animation will reset
imageView.startAnimation(rotateAnim);
Usually one can setup such View animations through XML as well. But, since you have to specify absolute degree values in there, successive rotations will repeat themselves instead of building upon the previous one to complete a full circle. Hence, I chose to show how to do it in code above.

ImageView getLocationtOnScreen android

I am trying to get the coordinates of the image on the screen. I currently have an ImageView within an activity. I understand that the getLocationOnScreen() method can only be called once the layout has been created, so calling this method within the oncreate function would return [0,0]. But I do not know how to get this method to return the correct values. I have tried overiding various superclass methods, like the onstart method or the onTouchEvent method and it still returns [0,0] to me. The code I currently have is as follows:
#Override
public void onCreate(Bundle savedInstanceState)
{
// Some code here after which ..
image = (ImageView) findViewById(R.id.imageVfi);
image.setImageBitmap(imageData.entrySet().iterator().next().getValue());
}
Then I have the onStart method which I have overriden
#Override
public void onStart()
{
super.onStart();
image.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
int[] dim = new int[2];
image.getLocationOnScreen(dim);
new AlertDialog.Builder(DisplayPicture.this)
.setIcon(R.drawable.icon)
.setTitle("Touch coordinates : " +
String.valueOf(dim[0]) + "x" + String.valueOf(dim[1]))
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
}
}).show();
// image calculations go here
return true;
}
});
}
This returns 0X0 to me. Any help is much appreciated.
ImageView does not offer a way to get the location of its image on screen. You can only query the location of the ImageView itself. You can try to use ImageView.getImageMatrix() but I'm not sure we populate it when the image is simply centered (as opposed to scaled, etc.)
Solution after following advice given above
Solution:
Following the advice provided by Romain Guy below, I was able to get the co-ordinates but adding the following code to the onStart overidden method.
display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
int orientation = display.getOrientation();
float rowStart=0, rowEnd=0, columnStart=0, columnEnd=0;
if(orientation ==0)
{
final Matrix matrix = image.getImageMatrix();
float[] values = new float[9];
matrix.getValues(values);
rowStart = values[0];
columnStart = values[5];
rowEnd = image.getWidth()-rowStart;
columnEnd = image.getHeight()-columnStart;
}else if(orientation == 1)
{
final Matrix matrix = image.getImageMatrix();
float[] values = new float[9];
matrix.getValues(values);
rowStart = values[2];
columnStart = values[3];
rowEnd = image.getWidth()-rowStart;
columnEnd = image.getHeight()-columnStart;
}
If it's only the image view that you have in your activity, then it will be positioned by default in the top left corner with coordinates 0x0.

Categories