there is a layout, where I have some buttons, controls and an imageView. When the layout shows up, everything is okay. But later, when the requested image (the image of the aveform) is downloaded and I try to set it to the ImageView with setImageBitmap. The whole layout become messed up. Here are some pics.
This is how the layout looks like, when image has not been downloaded:
This is after the setImageBitMap
Here is my xml (I use a custom subclass of imageView, but the error also occurs withz the original mageView)
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
>
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TableRow
android:id="#+id/tableRow1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center" >
<adam.czibere.WaveFormSurfaceView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<SeekBar
android:id="#+id/seekBar"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="20dp"
android:layout_gravity="center"
android:thumb="#drawable/progress_fill" />
</TableRow>
<TableRow
android:id="#+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/currentPos"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="right"
android:layout_weight="5"
android:text="00:00.000" />
<TextView
android:id="#+id/textView4"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:layout_weight="1"
android:text="/" />
<TextView
android:id="#+id/endPos"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="5"
android:gravity="left"
android:text="00:00.000" />
</TableRow>
<TableRow
android:id="#+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="#+id/closebtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Close" />
<Button
android:id="#+id/playButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Play" />
<ToggleButton
android:id="#+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="ToggleButton" />
</TableRow>
</TableLayout>
Here is the extended imageView:
public class WaveFormSurfaceView extends ImageView {
public boolean isEditMode = false;
Bitmap waveform = null;
int touchCount = 0;
List<VerbaComment> myComments = new ArrayList<VerbaComment>();
int lastTouch_x = -1;
public WaveFormSurfaceView(Context context) {
super(context);
}
public WaveFormSurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public WaveFormSurfaceView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
// copies the given waveform to a variable
public void setWaveForm(Bitmap b) {
waveform = Bitmap.createBitmap(b.getWidth(), b.getHeight(),
b.getConfig());
// copy the pixel to it
int[] allpixels = new int[b.getHeight() * b.getWidth()];
b.getPixels(allpixels, 0, b.getWidth(), 0, 0, b.getWidth(),
b.getHeight());
waveform.setPixels(allpixels, 0, b.getWidth(), 0, 0, b.getWidth(),
b.getHeight());
}
#Override
public void setImageBitmap(Bitmap bm) {
// TODO Auto-generated method stub
super.setImageBitmap(bm);
setWaveForm(bm);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// System.out.println("waveform width: "+waveform.getWidth());
// setMeasuredDimension(getMeasuredWidth(), getMeasuredHeight());
// setMeasuredDimension(widthMeasureSpec,heightMeasureSpec);
// setMeasuredDimension(1000,200);
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
// super.onDraw(canvas);
// Create a paint object for us to draw with, and set our drawing color
// to blue.
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setAlpha(50);
Paint paint1 = new Paint();
paint1.setColor(Color.GREEN);
paint1.setAlpha(50);
// draws the rectangle
if (waveform != null) {
canvas.drawBitmap(waveform, 0, 0, null);
if (isEditMode) {
for (VerbaComment vc : myComments) {
System.out.println("drawing the comment... start: "
+ vc.start + " end: " + vc.end);
canvas.drawRect(vc.start, canvas.getHeight(), vc.end, 0,
paint);
}
}
System.out.println("waveform width, height:" + waveform.getWidth()
+ " x " + waveform.getHeight());
} else {
canvas.drawRect(0, 0, 50, 50, paint);
}
// mImageView.setImageBitmap(map);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == MotionEvent.ACTION_UP) {
if (isEditMode) {
touchCount++;
// lastTouch_x=(int)event.getX();
// System.out.println("onTouch; touchCount: "+touchCount+" lasttouch_x: "+lastTouch_x);
if (touchCount % 2 == 0) {
VerbaComment temp = new VerbaComment(lastTouch_x,
(int) event.getX());
myComments.add(temp);
} else {
lastTouch_x = (int) event.getX();
System.out.println("onTouch; touchCount: " + touchCount
+ " lasttouch_x: " + lastTouch_x);
}
}
}
invalidate();
return true;
}
}
And here is the activity:
public class AudioPlayerActivity extends Activity{
// Hardcoded parameters for the Verba demo server
private static final String ServerURL = "http://demo.verba.com";
private static final String MediaPath = "C:\\Program%20Files\\Verba\\media\\";
// Player user interface elements
private Button mBtnPlay;
private WaveFormSurfaceView mImageView;
//private ImageView mImageView;
private SeekBar mSeekBar;
private TextView mCurrentPos;
private TextView mEndPos;
private Bitmap originalWaveForm;
// THIS IS THE MEDIAPLAYER (has no UI, only loads and plays the audio)
private MediaPlayer mMediaPlayer;
// HTTP URL for the audio waveform PNG picture
private String getWaveformURL(String pCallURL) {
return ServerURL + ":8089/a?" + MediaPath + pCallURL
+ "?10000200240240240123023048240240240240240240";
}
// HTTP URL for the audio transcoded to MP3 format
private String getMediaURL(String pCallURL) {
return ServerURL + ":10100/getMedia?file=" + MediaPath + pCallURL
+ "&format=mp3";
}
// Downloads the waveform image outside of the main GU thread
private class DownloadWaveformTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
try {
return BitmapFactory.decodeStream((InputStream) new URL(
getWaveformURL(myCallURL))
.getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
try {
Thread.sleep(50000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mImageView.setImageBitmap(result);
}
}
// Updates the seekbar outside of the main GU thread, started only after
// MediaPlayer exists
private class SeekBarUpdater extends Thread {
float p=0;
#Override
public void run() {
final SimpleDateFormat tf = new SimpleDateFormat("mm:ss.SSS");
final Calendar calendar = Calendar.getInstance();
int currentPosition = 0;
final int total = mMediaPlayer.getDuration(); // //returns in msec,
// final because we
// will use in the
// runnable
// UI update must happen on the UI thread, so we post our actions
// there in a runnable
mCurrentPos.post(new Runnable() {
public void run() {
calendar.setTimeInMillis(total);
mEndPos.setText(tf.format(calendar.getTime()));
mSeekBar.setMax(total);
}
});
while (mMediaPlayer != null && currentPosition < total) {
try {
Thread.sleep(50);
currentPosition = mMediaPlayer.getCurrentPosition(); // returns
// in
// msec
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
// we are roughly adjusting for delays due to the thread
// communication
// currentPosition -= 100;
// if (currentPosition < 0 ) currentPosition = 0;
final int currPosition = currentPosition; // final because we
// will use in the
// runnable
p=(float)currentPosition/(float)total;
// UI update must happen on the UI thread, so we post our
// actions there in a runnable
mCurrentPos.post(new Runnable() {
public void run() {
calendar.setTimeInMillis(currPosition);
mCurrentPos.setText(tf.format(calendar.getTime()));
mSeekBar.setProgress(currPosition);
System.out.println("pecent="+p);
drawRectOnWaveForm(p);
}
});
}
}
}
String myCallURL;
/**
* Create a new instance of MyFragment that will be initialized
* with the given arguments.
*/
static MediaPlayerFragment newInstance(CharSequence url) {
MediaPlayerFragment f = new MediaPlayerFragment();
Bundle args = new Bundle();
args.putCharSequence("call_url", url);
f.setArguments(args);
return f;
}
/**
* During creation, if arguments have been supplied to the fragment
* then parse those out.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value1 = extras.getString("call_url");
if(value1!=null){
myCallURL=value1;
}
}
DownloadWaveformTask task = new DownloadWaveformTask();
task.execute();
setContentView(R.layout.mediaplayer);
System.out.println("AudioPlayerActivity setContentView, mycallurl: "+myCallURL);
// part of the player UI
//mImageView = (ImageView) findViewById(R.id.imageView);
mImageView = (WaveFormSurfaceView) findViewById(R.id.imageView);
mBtnPlay = (Button) findViewById(R.id.playButton);
mSeekBar = (SeekBar) findViewById(R.id.seekBar);
mCurrentPos = (TextView) findViewById(R.id.currentPos);
mEndPos = (TextView) findViewById(R.id.endPos);
ToggleButton tb=(ToggleButton) findViewById(R.id.toggleButton1);
tb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
mImageView.isEditMode=true;
mImageView.invalidate();
}else{
mImageView.isEditMode=false;
mImageView.invalidate();
}
}
});
//
mSeekBar.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) {
if (fromUser) {
// we only update the player if the change comes from a user
// action
mMediaPlayer.seekTo(progress);
}
}
});
// IMPORTANT
// - The DownloadWaveformTask part should go into the initialization of
// the player fragment
// - currently we are NOT handling currently the end of playback
// situations, we should
// - currently we are NOT releasing the MediaPlayer resource, we should
// when a fragment closes
mBtnPlay.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mMediaPlayer != null) {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
mBtnPlay.setText("Play");
} else {
mMediaPlayer.start();
mBtnPlay.setText("Pause");
}
} else {
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
// this updates the seekbar as the buffering happens
mMediaPlayer
.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
#Override
public void onBufferingUpdate(MediaPlayer mp,
int percent) {
// TODO Auto-generated method stub
mSeekBar.setSecondaryProgress((int) (mSeekBar
.getMax() * percent / 100));
}
});
try {
final String lMediaURL = getMediaURL(myCallURL);
mMediaPlayer.setDataSource(lMediaURL);
mMediaPlayer.prepare(); // might take long! (for
// buffering, etc)
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mMediaPlayer.start();
mBtnPlay.setText("Pause");
// we start the thread that updates the seekbar, based on
// the state of the player
SeekBarUpdater thread = new SeekBarUpdater();
thread.start();
}
}
});
// Close button
Button closeBtn = (Button) findViewById(R.id.closebtn);
closeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//TODO ha megy a lejátszás, megállítjuk
if(mMediaPlayer!=null){
if(mMediaPlayer.isPlaying()){
mMediaPlayer.stop();
}
}
finish();
}
});
}
}
Okz here are some flaws i have got in your code
You are giving android:layout_gravity="center" to your SeekBar and on other hand you are giving it match_parent attribute
Why you are giving fill_parent to your id/tableRow3
and try to use fill_parent instead of match _parent because fill_parent is backword compatible
Related
I'm trying to upload an Image from my API to show it as profile picture, the problem is from the first time that the user opens the navdrawer the image doesn't load and it makes the entire layout disappear, but from the second time it all works, and I notice that it happens when the width of the image is less than the height. This is the class that I'm using:
public class CircledNetworkImageView extends ImageView {
public boolean mCircled;
/**
* The URL of the network image to load
*/
private String mUrl;
/**
* Resource ID of the image to be used as a placeholder until the network image is loaded.
*/
private int mDefaultImageId;
/**
* Resource ID of the image to be used if the network response fails.
*/
private int mErrorImageId;
/**
* Local copy of the ImageLoader.
*/
private ImageLoader mImageLoader;
/**
* Current ImageContainer. (either in-flight or finished)
*/
private ImageLoader.ImageContainer mImageContainer;
public CircledNetworkImageView(Context context) {
this(context, null);
}
public CircledNetworkImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CircledNetworkImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/**
* Sets URL of the image that should be loaded into this view. Note that calling this will
* immediately either set the cached image (if available) or the default image specified by
* {#link CircledNetworkImageView#setDefaultImageResId(int)} on the view.
* <p/>
* NOTE: If applicable, {#link CircledNetworkImageView#setDefaultImageResId(int)} and
* {#link CircledNetworkImageView#setErrorImageResId(int)} should be called prior to calling
* this function.
*
* #param url The URL that should be loaded into this ImageView.
* #param imageLoader ImageLoader that will be used to make the request.
*/
public void setImageUrl(String url, ImageLoader imageLoader) {
mUrl = url;
mImageLoader = imageLoader;
// The URL has potentially changed. See if we need to load it.
loadImageIfNecessary(false);
}
/**
* Sets the default image resource ID to be used for this view until the attempt to load it
* completes.
*/
public void setDefaultImageResId(int defaultImage) {
mDefaultImageId = defaultImage;
}
/**
* Sets the error image resource ID to be used for this view in the event that the image
* requested fails to load.
*/
public void setErrorImageResId(int errorImage) {
mErrorImageId = errorImage;
}
/**
* Loads the image for the view if it isn't already loaded.
*
* #param isInLayoutPass True if this was invoked from a layout pass, false otherwise.
*/
void loadImageIfNecessary(final boolean isInLayoutPass) {
int width = getWidth();
int height = getHeight();
ScaleType scaleType = getScaleType();
boolean wrapWidth = false, wrapHeight = false;
if (getLayoutParams() != null) {
wrapWidth = getLayoutParams().width == ViewGroup.LayoutParams.WRAP_CONTENT;
wrapHeight = getLayoutParams().height == ViewGroup.LayoutParams.WRAP_CONTENT;
}
// if the view's bounds aren't known yet, and this is not a wrap-content/wrap-content
// view, hold off on loading the image.
boolean isFullyWrapContent = wrapWidth && wrapHeight;
if (width == 0 && height == 0 && !isFullyWrapContent) {
return;
}
// if the URL to be loaded in this view is empty, cancel any old requests and clear the
// currently loaded image.
if (TextUtils.isEmpty(mUrl)) {
if (mImageContainer != null) {
mImageContainer.cancelRequest();
mImageContainer = null;
}
setDefaultImageOrNull();
return;
}
// if there was an old request in this view, check if it needs to be canceled.
if (mImageContainer != null && mImageContainer.getRequestUrl() != null) {
if (mImageContainer.getRequestUrl().equals(mUrl)) {
// if the request is from the same URL, return.
return;
} else {
// if there is a pre-existing request, cancel it if it's fetching a different URL.
mImageContainer.cancelRequest();
setDefaultImageOrNull();
}
}
// Calculate the max image width / height to use while ignoring WRAP_CONTENT dimens.
int maxWidth = wrapWidth ? 0 : width;
int maxHeight = wrapHeight ? 0 : height;
// The pre-existing content of this view didn't match the current URL. Load the new image
// from the network.
ImageLoader.ImageContainer newContainer = mImageLoader.get(mUrl,
new ImageLoader.ImageListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (mErrorImageId != 0) {
setImageResource(mErrorImageId);
}
}
#Override
public void onResponse(final ImageLoader.ImageContainer response, boolean isImmediate) {
// If this was an immediate response that was delivered inside of a layout
// pass do not set the image immediately as it will trigger a requestLayout
// inside of a layout. Instead, defer setting the image by posting back to
// the main thread.
if (isImmediate && isInLayoutPass) {
post(new Runnable() {
#Override
public void run() {
onResponse(response, false);
}
});
return;
}
if (response.getBitmap() != null) {
setImageBitmap(response.getBitmap());
} else if (mDefaultImageId != 0) {
setImageResource(mDefaultImageId);
}
}
}, maxWidth, maxHeight, scaleType);
// update the ImageContainer to be the new bitmap container.
mImageContainer = newContainer;
}
private void setDefaultImageOrNull() {
if (mDefaultImageId != 0) {
setImageResource(mDefaultImageId);
} else {
setImageBitmap(null);
}
}
#Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
loadImageIfNecessary(true);
}
#Override
protected void onDetachedFromWindow() {
if (mImageContainer != null) {
// If the view was bound to an image request, cancel it and clear
// out the image from the view.
mImageContainer.cancelRequest();
setImageBitmap(null);
// also clear out the container so we can reload the image if necessary.
mImageContainer = null;
}
super.onDetachedFromWindow();
}
#Override
protected void drawableStateChanged() {
super.drawableStateChanged();
invalidate();
}
/**
* In case the bitmap is manually changed, we make sure to
* circle it on the next onDraw
*/
#Override
public void setImageBitmap(Bitmap bm) {
mCircled = false;
super.setImageBitmap(bm);
}
/**
* In case the bitmap is manually changed, we make sure to
* circle it on the next onDraw
*/
#Override
public void setImageResource(int resId) {
mCircled = false;
super.setImageResource(resId);
}
/**
* In case the bitmap is manually changed, we make sure to
* circle it on the next onDraw
*/
#Override
public void setImageDrawable(Drawable drawable) {
mCircled = false;
super.setImageDrawable(drawable);
}
/**
* We want to make sure that the ImageView has the same height and width
*/
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Drawable drawable = getDrawable();
if (drawable != null) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int diw = drawable.getIntrinsicWidth();
if (diw > 0) {
int height = width * drawable.getIntrinsicHeight() / diw;
setMeasuredDimension(width, height);
} else
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
} else
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
#Override
protected void onDraw(Canvas canvas) {
//Let's circle the image
if (!mCircled && getDrawable() != null) {
Drawable d = getDrawable();
try {
//We use reflection here in case that the drawable isn't a
//BitmapDrawable but it contains a public getBitmap method.
Bitmap bitmap = (Bitmap) d.getClass().getMethod("getBitmap").invoke(d);
if (bitmap != null) {
Bitmap circleBitmap = getCircleBitmap(bitmap);
setImageBitmap(circleBitmap);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
//Seems like the current drawable is not a BitmapDrawable or
//that is doesn't have a public getBitmap() method.
}
//Mark as circled even if it failed, because if it fails once,
//It will fail again.
mCircled = true;
}
super.onDraw(canvas);
}
/**
* Method used to circle a bitmap.
*
* #param bitmap The bitmap to circle
* #return The circled bitmap
*/
public static Bitmap getCircleBitmap(Bitmap bitmap) {
int size = Math.min(bitmap.getWidth(), bitmap.getHeight());
Bitmap output = Bitmap.createBitmap(size,
size, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
BitmapShader shader;
shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP,
Shader.TileMode.CLAMP);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(shader);
paint.setAlpha(254);
RectF rect = new RectF(0, 0, size, size);
int radius = size / 2;
canvas.drawRoundRect(rect, radius, radius, paint);
return output;
}
}
I came up with that solution, but I didn't like it, because the image loses its quality:
public class UserActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_main);
toolbar = (Toolbar) findViewById(R.id.toolbar_user);
camera = (ImageView) findViewById(R.id.camera);
fechar = (TextView) findViewById(R.id.fechar);
editar = (TextView) findViewById(R.id.editar);
membro = (TextView) findViewById(R.id.membro);
nome = (TextView) findViewById(R.id.nome_usuario);
email = (TextView) findViewById(R.id.email_usuario);
email = (TextView) findViewById(R.id.email_usuario);
profilePic = (NetworkImageView) findViewById(R.id.foto);
mImageView = (ImageView) findViewById(R.id.cropped);
progress_wheel = (ProgressWheel) findViewById(R.id.progress_wheel);
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder getImageFrom = new AlertDialog.Builder(UserActivity.this);
getImageFrom.setTitle("Abrir com:");
final CharSequence[] opsChars = {getResources().getString(R.string.takepic), getResources().getString(R.string.opengallery)};
getImageFrom.setItems(opsChars, new android.content.DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else if (which == 1) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
}
dialog.dismiss();
}
});
getImageFrom.show();
}
});
profilePic.setImageUrl(GlobalModel.getPerfil().getIdDaImagem(), imageLoader);
profilePic.setDefaultImageResId(R.drawable.avatar_);
}
#Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (resultCode != RESULT_OK) return;
switch (requestCode) {
case PICK_FROM_CAMERA:
profilePic.setVisibility(View.GONE);
progress_wheel.setVisibility(View.VISIBLE);
selectedImagePath = ImageFilePath.getPath(getApplicationContext(), mImageCaptureUri);
Log.i("Image File Path", "" + selectedImagePath);
mImageCaptureUri = Uri.parse(selectedImagePath);
final BitmapFactory.Options option = new BitmapFactory.Options();
option.inSampleSize = 8;
Bitmap photo = BitmapFactory.decodeFile(mImageCaptureUri.getPath(), option);
photo = Bitmap.createScaledBitmap(photo, 200, 200, false);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "Imagename.jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
previewCapturedImage(f.getAbsolutePath());
profilePic.setVisibility(View.VISIBLE);
progress_wheel.setVisibility(View.GONE);
profilePic.setImageBitmap(BitmapFactory.decodeFile(mImageCaptureUri.getPath()));
break;
case PICK_FROM_FILE:
profilePic.setVisibility(View.GONE);
progress_wheel.setVisibility(View.VISIBLE);
mImageCaptureUri = data.getData();
selectedImagePath = ImageFilePath.getPath(getApplicationContext(), mImageCaptureUri);
Log.i("Image File Path", "" + selectedImagePath);
mImageCaptureUri = Uri.parse(selectedImagePath);
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap photoGaleria = BitmapFactory.decodeFile(mImageCaptureUri.getPath(), options);
photoGaleria = Bitmap.createScaledBitmap(photoGaleria, 200, 200, false);
ByteArrayOutputStream bytesG = new ByteArrayOutputStream();
photoGaleria.compress(Bitmap.CompressFormat.JPEG, 100, bytesG);
File fG = new File(Environment.getExternalStorageDirectory()
+ File.separator + "Imagename.jpg");
fG.createNewFile();
FileOutputStream foG = new FileOutputStream(fG);
foG.write(bytesG.toByteArray());
foG.close();
previewCapturedImage(fG.getAbsolutePath());
profilePic.setVisibility(View.VISIBLE);
progress_wheel.setVisibility(View.GONE);
profilePic.setImageBitmap(BitmapFactory.decodeFile(mImageCaptureUri.getPath()));
break;
}
} catch (Exception e)
{
e.printStackTrace();
}
}
private void previewCapturedImage(String path) {
try {
UploadFoto mUpload = new UploadFoto(path);
mUpload.setEventoListener(new IExecutarTarefa<UploadFoto>() {
#Override
public void AntesDeExecutar(UploadFoto tarefa) {
}
#Override
public void DepoisDeExecutar(UploadFoto tarefa) {
if (tarefa.getResposta()[0].equals("200")) {
GlobalModel.getPerfil().setIdDaImagem(WebService.imgURL + tarefa.getResposta()[1].replace("\"", ""));
profilePic.setImageUrl(GlobalModel.getPerfil().getIdDaImagem(), imageLoader);
}
}
});
mUpload.execute();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
overridePendingTransition(R.anim.animation_back, R.anim.animation_back_leave);
}
#Override
protected void onResume() {
super.onResume();
CarregarPerfil mCarrega = new CarregarPerfil();
mCarrega.execute();
}
}
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
xmlns:wheel="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
<include
android:id="#+id/toolbar_user"
layout="#layout/toolbaruser" />
<RelativeLayout
android:id="#+id/campoImagem"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:layout_below="#+id/toolbar_user"
android:background="#color/armadillo">
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/foto"
android:layout_width="200dp"
android:layout_height="fill_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="#drawable/user"
android:visibility="visible" />
<com.pnikosis.materialishprogress.ProgressWheel
android:id="#+id/progress_wheel"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_gravity="center"
android:visibility="gone"
wheel:matProg_barColor="#color/white"
wheel:matProg_progressIndeterminate="true"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<ImageView
android:id="#+id/cropped"
android:layout_width="200dp"
android:layout_height="fill_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:visibility="visible"/>
<ImageView
android:id="#+id/camera"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:padding="15dp"
android:src="#drawable/ic_camera" />
<TextView
android:id="#+id/Button_crop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:gravity="center"
android:padding="15dp"
android:text="Salvar"
android:textColor="#color/white"
android:visibility="gone" />
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<TextView
android:id="#+id/membro"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:gravity="center"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingTop="5dp"
android:text="Membro Retornar desde Julho de 2015"
android:textColor="#color/star_dust" />
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/campoImagem"
android:layout_marginBottom="30dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp"
android:gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingBottom="0dp"
android:paddingLeft="10dp"
android:paddingRight="0dp"
android:paddingTop="10dp"
android:text="Nome"
android:textColor="#color/star_dust"
android:textSize="#dimen/text1" />
<TextView
android:id="#+id/nome_usuario"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingBottom="0dp"
android:paddingLeft="10dp"
android:paddingTop="5dp"
android:textColor="#color/armadillo"
android:textSize="#dimen/text1" />
<TextView
android:id="#+id/entrar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="10dp"
android:paddingTop="10dp"
android:text="E-mail"
android:textColor="#color/star_dust"
android:textSize="#dimen/text1" />
<TextView
android:id="#+id/email_usuario"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingBottom="0dp"
android:paddingLeft="10dp"
android:paddingTop="5dp"
android:text="jgvidotto#gmail.com"
android:textColor="#color/armadillo"
android:textSize="#dimen/text1" />
</LinearLayout>
</RelativeLayout>
Because you have not posted your Activity calling the Navigation Drawer, so I have used both your CircledNetworkImageView class and built-in NetworkImageView in my project. It works well. Please refer to the following:
CustomNavigationDrawer.java:
public class CustomNavigationDrawer {
private static ActionBarDrawerToggle sDrawerToggle;
public static DrawerLayout setUpDrawer(final Context context) {
final Activity activity = ((Activity) context);
DrawerLayout sDrawerLayout = (DrawerLayout) activity.findViewById(R.id.drawer_layout);
if (activity.getActionBar() != null) {
activity.getActionBar().setDisplayHomeAsUpEnabled(true);
activity.getActionBar().setHomeButtonEnabled(true);
}
sDrawerToggle = new ActionBarDrawerToggle(
activity,
sDrawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close
) {
public void onDrawerClosed(View view) {
activity.invalidateOptionsMenu();
syncState();
}
public void onDrawerOpened(View drawerView) {
activity.invalidateOptionsMenu();
syncState();
}
};
sDrawerLayout.setDrawerListener(sDrawerToggle);
return sDrawerLayout;
}
public static void syncState() {
sDrawerToggle.syncState();
}
public static void onConfigurationChanged(Configuration newConfig) {
sDrawerToggle.onConfigurationChanged(newConfig);
}
}
MainActivity.java:
public class MainActivity extends Activity {
final Context mContext = this;
final String mUrl = "http://.../getimage";
NetworkImageView mNetworkImageView;
CircledNetworkImageView mCircledNetworkImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomNavigationDrawer.setUpDrawer(this);
mNetworkImageView = (NetworkImageView) findViewById(R.id.networkImageView);
mNetworkImageView.setImageUrl(mUrl, VolleySingleton.getInstance(mContext).getImageLoader());
mCircledNetworkImageView = (CircledNetworkImageView) findViewById(R.id.circleImageView);
mCircledNetworkImageView.setImageUrl(mUrl, VolleySingleton.getInstance(mContext).getImageLoader());
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
CustomNavigationDrawer.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
CustomNavigationDrawer.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
activity_main.xml:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/networkImageView"
android:layout_width="300dp"
android:layout_height="wrap_content" />
<com.example.networkimageview.CircledNetworkImageView
android:id="#+id/circleImageView"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="#+id/networkImageView" />
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
You can create a new sample project and use my sample code. Hope this helps!
if (width == 0 && height == 0 && !isFullyWrapContent) {
I guess the first you loadImage code will return because of this condition. The width and height is equal to 0 before the whole UI load success. log before this condition return. Hope this can help you.
I have made a demo project for image rotation in seekbar progresschange. I have successfully done it on button change but its not working on seekbar change. Here is what I tried:
xml
<ImageView
android:id="#+id/iv_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/enr" />
<SeekBar
android:id="#+id/seekbar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="20dp"
android:max="360"
android:padding="1dp"
android:progress="0" />
<Button
android:id="#+id/bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/seekbar"
android:layout_centerHorizontal="true"
android:text="Rotate" />
code
public class MainActivity extends Activity implements OnSeekBarChangeListener {
ImageView iv_image;
SeekBar seekbar;
Bitmap source;
float angle = 0;
Button buttonClick;
Bitmap rotatedImage;
static Matrix matrix;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
buttonClick = (Button) findViewById(R.id.bt);
buttonClick.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
angle += 90;
iv_image.buildDrawingCache();
source = iv_image.getDrawingCache();
rotatedImage = rotateImage(source, angle);
iv_image.setImageBitmap(rotatedImage);
}
});
}
void init() {
iv_image = (ImageView) findViewById(R.id.iv_image);
seekbar = (SeekBar) findViewById(R.id.seekbar);
seekbar.setOnSeekBarChangeListener(this);
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
angle = progress;
iv_image.buildDrawingCache();
source = iv_image.getDrawingCache();
rotatedImage = rotateImage(source, angle);
iv_image.setImageBitmap(null);
iv_image.setImageBitmap(rotatedImage);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public static Bitmap rotateImage(Bitmap sourceImage, float angle) {
matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(sourceImage, 0, 0, sourceImage.getWidth(),
sourceImage.getHeight(), matrix, true);
}
}
You forgot to attach OnSeekBarChangeListener to your SeekBar:
void init() {
iv_image = (ImageView) findViewById(R.id.iv_image);
seekbar = (SeekBar) findViewById(R.id.seekbar);
seekbar.setOnSeekBarChangeListener(this); // <-----
}
I suggest you use the Picasso library by Square. It will be much simpler and straightforward for this need here
Here am developed a puzzle game, image tiles place in gridview, but the thing is, I would like to fill complete device screen width or device screen height with those tiles.
Here is my result.
Here is my code, please tell me where am doing mistake.
public class ImageBreaking_Activity extends Activity implements OnClickListener {
Button b_save, view_bb;
private Bitmap b;
int position;
ImageButton b_90, b_360;
GridView grid;
String filePath,biks;
Bitmap selectedphoto_bitmap;
int row, col, val;
ArrayList<Bitmap> imageChunks = new ArrayList<Bitmap>();
ArrayList<Bitmap> imageChunks_child = new ArrayList<Bitmap>();
ArrayList<Bitmap> duplicate_bitmaps, duplicate_bitmaps_dump;
public ArrayList<MyBitamp> itemList_dump = new ArrayList<MyBitamp>();
public ArrayList<MyBitamp> itemList_dump__c = new ArrayList<MyBitamp>();
View v_duplicate;
private int count;
ImageAdapter__c adapter;
boolean clicked = false;
private int touchedItemPos = 0;
private MyBitamp tile;
AlertDialog.Builder ad;
DisplayMetrics metrics;
private int Screenwidth;
private int Screenheight;
int gameScreen_width,gameScreen_height;
private int width_bitmap;
private int height_bitmap;
#SuppressWarnings("static-access")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_breaking_);
// screen width x Height
grid = (GridView) findViewById(R.id.grid);
b_90 = (ImageButton) findViewById(R.id.imageButton1);
b_90.setOnClickListener(this);
view_bb = (Button) findViewById(R.id.button2);
view_bb.setOnClickListener(this);
b_360 = (ImageButton) findViewById(R.id.imageButton2);
b_360.setOnClickListener(this);
// side vices
filePath = this.getIntent().getStringExtra("File_path");
biks = this.getIntent().getExtras().getString("File_path_biks");
Log.i("W x H", "biks:" + biks);
selectedphoto_bitmap = decodeFile(filePath);
Log.i("Bitmap Width x Height", selectedphoto_bitmap.getWidth()+"& &"+selectedphoto_bitmap.getHeight());
// bitmap width x height
width_bitmap=selectedphoto_bitmap.getWidth();
height_bitmap=selectedphoto_bitmap.getHeight();
if(selectedphoto_bitmap.getWidth()>selectedphoto_bitmap.getHeight()){
val = selectedphoto_bitmap.getWidth()%selectedphoto_bitmap.getHeight();
// showing if bitmap width is higher than bitmap height, then rotating to 90 degrees
Matrix matrix = new Matrix();
matrix.postRotate(90);
selectedphoto_bitmap = Bitmap.createBitmap(selectedphoto_bitmap, 0, 0,
selectedphoto_bitmap.getWidth(), selectedphoto_bitmap.getHeight(),
matrix, true);
}else{
val=selectedphoto_bitmap.getHeight()%selectedphoto_bitmap.getWidth();
}
// for rows and cols
col=selectedphoto_bitmap.getWidth()/val;
row=selectedphoto_bitmap.getHeight()/val;
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
break_up(selectedphoto_bitmap);
super.onStart();
}
private void break_up(Bitmap selectedphoto_bitmap) {
// TODO Auto-generated method stub
int chunkHeight, chunkWidth,A;
imageChunks = new ArrayList<Bitmap>(col * row);// size of array let us go for 12 or 16
// for perfect square tile
chunkHeight = selectedphoto_bitmap.getHeight() / row;// setting height for tile
chunkWidth = selectedphoto_bitmap.getWidth() / col;// setting width for tile
Log.i("Main Activity_chuck bitmap", chunkHeight
+ " <--chunk__h & chunk__w-->" + chunkWidth);
Log.i("Main Activity_bitmap row and col", col + ":cols & Rows:" + row);
int yCoord = 0;
for (int x = 0; x < row; x++) {
int xCoord = 0;
for (int y = 0; y < col; y++) {
// adding those tile to the array
imageChunks.add(Bitmap.createBitmap(selectedphoto_bitmap,
xCoord, yCoord, chunkWidth, chunkHeight));
xCoord += chunkWidth;
Log.i("Array bitmap", "" + imageChunks.get(y).getWidth()
+ "<-- w & H-->" + imageChunks.get(y).getHeight());
}
yCoord += chunkHeight;
}
Log.i("TAG", "no of size" + imageChunks);
Log.i("TAG", "no of size" + imageChunks.size());
}
private Bitmap decodeFile(String f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale++;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
return null;
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
for (int i = 0, j = imageChunks.size(); i < j; i++) {
// taken one model class and passing width,height, id, item_position, rotation
MyBitamp item_dump = new MyBitamp(imageChunks.get(i)
.getWidth(), imageChunks.get(i).getHeight(),
imageChunks.get(i), i, i, 0);
itemList_dump.add(item_dump);
}
Collections.shuffle(itemList_dump);// shuffling the items
Random randomGenerator = new Random();// random number for rotation
int randomInt = randomGenerator.nextInt(4);
for (int i = 0, j = itemList_dump.size(); i < j; i++) {
itemList_dump.get(i).setItemCurPos(i);// set the item current position
itemList_dump.get(i).setrotation(randomInt);// set the rotation
}
adapter = new ImageAdapter__c(this);// custom adapter
grid.setAdapter(adapter);
grid.setNumColumns(col);
grid.setColumnWidth(imageChunks.get(0).getWidth());
grid.setStretchMode(GridView.NO_STRETCH);
super.onResume();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
Toast.makeText(this, "Clicked on save", 1).show();
break;
case R.id.imageButton1:
/* rotate view */
tile = itemList_dump.get(touchedItemPos);
if (b_90.isEnabled() && clicked) {
int fix_rotation = tile.getrotation();
if (fix_rotation != 0) {
if (fix_rotation == 0) {
fix_rotation = 0;
tile.setrotation(fix_rotation);
} else {
if (fix_rotation == 2) {
tile.setrotation(3);
} else
if (fix_rotation == 1) {
tile.setrotation(2);
} else if (fix_rotation == 3) {
tile.setrotation(0);
}
}
} else {
tile.setrotation(1);
// itemList_dump.get(position).setrotation(1);
}
} else {
Toast.makeText(ImageBreaking_Activity.this,
"select the item to rotate", Toast.LENGTH_LONG).show();
}
adapter.notifyDataSetChanged();
break;
case R.id.imageButton2:
if (b_360.isEnabled() && clicked) {
tile = itemList_dump.get(touchedItemPos);
int fix_rotation__c = (int) tile.getrotation();
if (fix_rotation__c != 0) {
if (fix_rotation__c == 1) {
tile.setrotation(0);
} else if (fix_rotation__c == 2) {
tile.setrotation(1);
} else if (fix_rotation__c == 3) {
tile.setrotation(2);
}
} else {
tile.setrotation(3);
}
} else {
Toast.makeText(ImageBreaking_Activity.this,
"Select item to Rotate", Toast.LENGTH_SHORT).show();
}
adapter.notifyDataSetChanged();
break;
case R.id.button2:
Dialog d = new Dialog(this);
d.setContentView(R.layout.dialog_xml);
ImageView img = (ImageView) d.findViewById(R.id.imageView1);
img.setImageBitmap(selectedphoto_bitmap);
d.show();
break;
default:
break;
}
}
public class ImageAdapter__c extends BaseAdapter implements
OnTouchListener, OnDragListener {
Context context;
int coordinates[] = new int[2];
ArrayList<MyBitamp> item_list_data = new ArrayList<MyBitamp>();
ArrayList<Bitmap> duplicate = new ArrayList<Bitmap>();
Bitmap b;
HashMap<View, Integer> hashMap = new HashMap<View, Integer>();
// ArrayList<MyBitamp> item_list_data_mybit = new ArrayList<MyBitamp>();
int i = 0, temp, temp2, count = 0, mod, position;
private int dest;
private int source;
private ImageView img;
private Integer touchedItemPosition;
private Integer dropedItemPosition;
private MyBitamp Data;
public ImageAdapter__c(ImageBreaking_Activity context) {
// TODO Auto-generated constructor stub
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return itemList_dump.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return itemList_dump.size();
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int pos, View v, ViewGroup parent) {
// TODO Auto-generated method stub
img = new ImageView(context);
Data = itemList_dump.get(pos);
Data.setItemCurPos(pos);
img.setLayoutParams(new GridView.LayoutParams(itemList_dump
.get(pos).getWidth(), itemList_dump.get(pos).getHeight()));
img.setPadding(1, 1, 1, 1);
img.setImageBitmap(itemList_dump.get(pos).getImageRes());
// rotation
int r_tation__C = itemList_dump.get(pos).getrotation();
if (r_tation__C == 0) {
img.setRotation(0);
} else if (r_tation__C == 1) {
img.setRotation(90);
} else if (r_tation__C == 2) {
img.setRotation(180);
} else if (r_tation__C == 3) {
img.setRotation(270);
}
else {
img.setRotation(360);
}
img.setOnTouchListener(this);
img.setOnDragListener(this);
hashMap.put(img, pos);
if (check_result()) {
Toast.makeText(ImageBreaking_Activity.this, "Success",
Toast.LENGTH_SHORT).show();
ad = new AlertDialog.Builder(ImageBreaking_Activity.this);
ad.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
Intent i_home = new Intent(
ImageBreaking_Activity.this,
HomePage.class);
i_home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i_home);
ImageBreaking_Activity.this.finish();
}
});
ad.setMessage("Congratulations....!");
ad.setCancelable(false);
ad.show();
}
// more work//
return img;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
v_duplicate = v;
clicked = true;
ClipData data = ClipData.newPlainText("", "");
DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(v);
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (hashMap.containsKey(v)) {
touchedItemPosition = hashMap.get(v);
touchedItemPos = touchedItemPosition;
MyBitamp bitamp = itemList_dump.get(touchedItemPos);
// Toast.makeText(context,
// "current pos:"+bitamp.getItemCurPos()+"original pos"+bitamp.getItemPosition(),Toast.LENGTH_SHORT).show();
v.startDrag(data, shadowBuilder, v, 0);
// item_list_data.get(touchedItemPosition);
}
v.setVisibility(View.INVISIBLE);
return true;
} else
if (event.getAction() == MotionEvent.ACTION_CANCEL) {
v.setVisibility(View.VISIBLE);
return false;
}
else
if (event.getAction() == MotionEvent.ACTION_MOVE) {
return false;
}
else if (event.getAction() == MotionEvent.ACTION_UP) {
}
return false;
}
#Override
public boolean onDrag(View v, DragEvent event) {
dropedItemPosition = hashMap.get(v);
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
// do nothing
break;
case DragEvent.ACTION_DRAG_ENTERED:
break;
case DragEvent.ACTION_DRAG_EXITED:
break;
case DragEvent.ACTION_DROP:
swapItemPositions(dropedItemPosition, touchedItemPosition);
break;
case DragEvent.ACTION_DRAG_ENDED:
Log.i("Drop", "end");
default:
break;
}
return true;
}
void swapItemPositions(int current, int target) {
MyBitamp tempBitmap = itemList_dump.get(current);
itemList_dump.set(current, itemList_dump.get(target));
itemList_dump.set(target, tempBitmap);
notifyDataSetChanged();
}
private boolean check_result() {
boolean isCompleted = false;
for (int i = 0; i < itemList_dump.size(); i++) {
int posit_fix = itemList_dump.get(i).getItemPosition();
int posit_current = itemList_dump.get(i).getItemCurPos();
int rotation = itemList_dump.get(i).getrotation();
if (((posit_fix == posit_current) && rotation == 0)) {
isCompleted = true;
} else {
isCompleted = false;
break;
}
}
if (isCompleted) {
// success
} else {
// failure
}
return isCompleted;
}
}
}
My xml file,
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#223344" >
<GridView
android:id="#+id/grid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/linearLayout1"
android:layout_alignParentRight="true" >
</GridView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="SAVE" />
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:enabled="true"
android:src="#drawable/plus_90" />
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:enabled="true"
android:src="#drawable/minus_90" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="VIEW" />
</LinearLayout>
</RelativeLayout>
Provide solution, Thank you
You should use Gridview width as fill_parent or match_parent. Currently you are using wrap_content which gives the grid only the space contained by your ImageView. Thats why you are getting the gap
<GridView
android:id="#+id/grid"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/linearLayout1"
>
</GridView>
Hope this helps.
Use this grid view
<GridView
android:id="#+id/grid"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="5dp"
android:columnWidth="100dp"
android:fastScrollEnabled="true"
android:horizontalSpacing="10dp"
android:numColumns="3"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp"
/>
change your gridview like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#223344" >
<GridView
android:id="#+id/grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/linearLayout1"
>
</GridView>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="SAVE" />
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:enabled="true"
android:src="#drawable/plus_90" />
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:enabled="true"
android:src="#drawable/minus_90" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="VIEW" />
</LinearLayout>
</RelativeLayout>
i want to create one screen for my android application in this application i want to create sliding navigation feature which is full visible on swipe (Left to Right ) and when user again swipe (RIght to Left ) it again swipe and close navigation window half and display half screen , i have used navigation drawer but i am not aware with this so please some help me if you have any code so please send me its will be my pleasure .
i am sending one image for reference where .
Find below code create a class AnimationLayout
import usb.terminal.R;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
public class AnimationLayout extends ViewGroup {
public final static int DURATION = 1000;
protected boolean mPlaceLeft = true;
public boolean mOpened;
protected View mSidebar;
protected View mContent;
protected int mSidebarWidth = 100; /*
* assign default value. It will be
* overwrite in onMeasure by Layout xml
* resource.
*/
protected Animation mAnimation;
protected OpenListener mOpenListener;
protected CloseListener mCloseListener;
protected Listener mListener;
protected boolean mPressed = false;
public AnimationLayout(Context context) {
this(context, null);
}
public AnimationLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public void onFinishInflate() {
super.onFinishInflate();
mSidebar = findViewById(R.id.animation_layout_sidebar);
mContent = findViewById(R.id.animation_layout_content);
if (mSidebar == null) {
throw new NullPointerException("no view id = animation_sidebar");
}
if (mContent == null) {
throw new NullPointerException("no view id = animation_content");
}
mOpenListener = new OpenListener(mSidebar, mContent);
mCloseListener = new CloseListener(mSidebar, mContent);
}
#Override
public void onLayout(boolean changed, int l, int t, int r, int b) {
/* the title bar assign top padding, drop it */
int sidebarLeft = l;
if (!mPlaceLeft) {
sidebarLeft = r - mSidebarWidth;
}
mSidebar.layout(sidebarLeft, 0, sidebarLeft + mSidebarWidth,
0 + mSidebar.getMeasuredHeight());
if (mOpened) {
if (mPlaceLeft) {
mContent.layout(l + mSidebarWidth, 0, r + mSidebarWidth, b);
} else {
mContent.layout(l - mSidebarWidth, 0, r - mSidebarWidth, b);
}
} else {
mContent.layout(l, 0, r, b);
}
}
#Override
public void onMeasure(int w, int h) {
super.onMeasure(w, h);
super.measureChildren(w, h);
mSidebarWidth = mSidebar.getMeasuredWidth();
}
#Override
protected void measureChild(View child, int parentWSpec, int parentHSpec) {
/* the max width of Sidebar is 90% of Parent */
if (child == mSidebar) {
int mode = MeasureSpec.getMode(parentWSpec);
int width = (int) (getMeasuredWidth() * 0.9);
super.measureChild(child, MeasureSpec.makeMeasureSpec(width, mode),
parentHSpec);
} else {
super.measureChild(child, parentWSpec, parentHSpec);
}
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (!isOpening()) {
return false;
}
int action = ev.getAction();
if (action != MotionEvent.ACTION_UP
&& action != MotionEvent.ACTION_DOWN) {
return false;
}
/*
* if user press and release both on Content while sidebar is opening,
* call listener. otherwise, pass the event to child.
*/
int x = (int) ev.getX();
int y = (int) ev.getY();
if (mContent.getLeft() < x && mContent.getRight() > x
&& mContent.getTop() < y && mContent.getBottom() > y) {
if (action == MotionEvent.ACTION_DOWN) {
mPressed = true;
}
if (mPressed && action == MotionEvent.ACTION_UP
&& mListener != null) {
mPressed = false;
return mListener.onContentTouchedWhenOpening();
}
} else {
mPressed = false;
}
return false;
}
public void setListener(Listener l) {
mListener = l;
}
/* to see if the Sidebar is visible */
public boolean isOpening() {
return mOpened;
}
public void toggleSidebar() {
if (mContent.getAnimation() != null) {
return;
}
if (mOpened) {
/* opened, make close animation */
if (mPlaceLeft) {
mAnimation = new TranslateAnimation(0, -mSidebarWidth, 0, 0);
} else {
mAnimation = new TranslateAnimation(0, mSidebarWidth, 0, 0);
}
mAnimation.setAnimationListener(mCloseListener);
} else {
/* not opened, make open animation */
if (mPlaceLeft) {
mAnimation = new TranslateAnimation(0, mSidebarWidth, 0, 0);
} else {
mAnimation = new TranslateAnimation(0, -mSidebarWidth, 0, 0);
}
mAnimation.setAnimationListener(mOpenListener);
}
mAnimation.setDuration(DURATION);
mAnimation.setFillAfter(true);
mAnimation.setFillEnabled(true);
mContent.startAnimation(mAnimation);
}
public void openSidebar() {
if (!mOpened) {
toggleSidebar();
}
}
public void closeSidebar() {
if (mOpened) {
toggleSidebar();
}
}
class OpenListener implements Animation.AnimationListener {
View iSidebar;
View iContent;
OpenListener(View sidebar, View content) {
iSidebar = sidebar;
iContent = content;
}
public void onAnimationRepeat(Animation animation) {
}
public void onAnimationStart(Animation animation) {
iSidebar.setVisibility(View.VISIBLE);
}
public void onAnimationEnd(Animation animation) {
iContent.clearAnimation();
mOpened = !mOpened;
requestLayout();
if (mListener != null) {
mListener.onSidebarOpened();
}
}
}
class CloseListener implements Animation.AnimationListener {
View iSidebar;
View iContent;
CloseListener(View sidebar, View content) {
iSidebar = sidebar;
iContent = content;
}
public void onAnimationRepeat(Animation animation) {
}
public void onAnimationStart(Animation animation) {
}
public void onAnimationEnd(Animation animation) {
iContent.clearAnimation();
iSidebar.setVisibility(View.INVISIBLE);
mOpened = !mOpened;
requestLayout();
if (mListener != null) {
mListener.onSidebarClosed();
}
}
}
public interface Listener {
public void onSidebarOpened();
public void onSidebarClosed();
public boolean onContentTouchedWhenOpening();
}
}
create a mainlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<yourpackage..AnimationLayout
android:id="#+id/animation_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!--Create you Layout which you want and just call in this include-->
<include
android:id="#id/animation_layout_sidebar"
android:layout_width="470dp"
android:layout_height="match_parent"
layout="#layout/my_cook_menu"
android:orientation="vertical" >
</include>
<!--Create you Layout which you want and just call in this include-->
<include
android:id="#id/animation_layout_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
layout="#layout/sound_my_cook"
android:clickable="true"
android:focusable="true"
android:orientation="vertical" >
</include>
</yourpackage.AnimationLayout>
</RelativeLayout>
</RelativeLayout>
create id.xml in values folder
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item type="id" name="animation_layout_sidebar" />
<item type="id" name="animation_layout_content" />
</resources>
write this code in which activity you are calling
public class MainActivity extends Activity implements
AnimationLayout.Listener, OnClickListener{
AnimationDrawable frameAnimation;
AnimationLayout animationLayout;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mainlayout);
}
public void onClick(View v) {
try {
animationLayout = (AnimationLayout) findViewById(R.id.animation_layout);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
animationLayout.toggleSidebar();
}
#Override
public void onSidebarOpened() {
// TODO Auto-generated method stub
}
#Override
public void onSidebarClosed() {
// TODO Auto-generated method stub
}
#Override
public boolean onContentTouchedWhenOpening() {
// TODO Auto-generated method stub
return false;
}
}
I haven't tried it yet but I think DrawerLayout recently added to support library could give you what you need. Here is the link for documentation. This is something what Facebook app is using to slide a pannel from left to right. Here is the tutorial.
I am new to Android and I am trying to add start and reset buttons with a custom surface view. I am able to draw canvas with a circle which is moving with touch.
Now my problem is that when I click the start button, the circle must take its initial position (10,10).
My activity class
public class OpenGlActivity extends Activity implements OnClickListener {
GameView GameView;
FrameLayout Frame;
LinearLayout canvas;
Button btnStart, btnReset;
TutorialThread GameThread;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set full screen view
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
GameView = new GameView(this);
btnStart = (Button) findViewById(R.id.btnStart);
btnStart.setOnClickListener(this);
btnReset = (Button) findViewById(R.id.btnReset);
btnReset.setOnClickListener(this);
GameView.setOnTouchListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStart:
Log.i("openGl", "play called");
GameView.setState();
// drawView.invalidate();
break;
case R.id.btnReset:
// GameView.play=true;
// GameView.reset();
Log.i("openGl", "RESETcalled");
// drawView.invalidate();
break;
}
}
}
Custom surfaceview class and thread class
class GameView extends SurfaceView implements SurfaceHolder.Callback {
String TAG = "GameView";
private TutorialThread _thread;
Paint paint = new Paint();
Paint red = new Paint();
Paint black = new Paint();
int x = 20;
int y = 20;
public GameView(Context context) {
super(context);
// TODO Auto-generated constructor stub
getHolder().addCallback(this);
_thread = new TutorialThread(getHolder(), this);
// TODO Auto-generated constructor stub
paint.setColor(Color.WHITE);
paint.setAntiAlias(true);
red.setColor(Color.RED);
red.setAntiAlias(true);
black.setColor(Color.BLACK);
black.setAntiAlias(true);
setFocusable(true);
}
public GameView(Context context, AttributeSet attrs) {
super(context, attrs);
getHolder().addCallback(this);
_thread = new TutorialThread(getHolder(), this);
// TODO Auto-generated constructor stub
paint.setColor(Color.WHITE);
paint.setAntiAlias(true);
red.setColor(Color.RED);
red.setAntiAlias(true);
black.setColor(Color.BLACK);
black.setAntiAlias(true);
setFocusable(true);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
x = (int) event.getX();
y = (int) event.getY();
return true;
}
public void setState() {
Log.i(TAG, "in setState");
_thread.play();
}
#Override
public void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
canvas.drawCircle(x, y, 10, red);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
_thread.setRunning(true);
_thread.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// simply copied from sample application LunarLander:
// we have to tell thread to shut down & wait for it to finish, or else
// it might touch the Surface after we return and explode
boolean retry = true;
_thread.setRunning(false);
while (retry) {
try {
_thread.join();
retry = false;
} catch (InterruptedException e) {
// we will try it again and again...
}
}
}
}
class TutorialThread extends Thread {
String TAG = "TutorialThread";
private SurfaceHolder _surfaceHolder;
private GameView _panel;
private boolean _run = false;
public TutorialThread(SurfaceHolder surfaceHolder, GameView panel) {
_surfaceHolder = surfaceHolder;
_panel = panel;
}
public void setRunning(boolean run) {
_run = run;
}
#Override
public void run() {
Canvas c;
while (_run) {
c = null;
try {
c = _surfaceHolder.lockCanvas(null);
synchronized (_surfaceHolder) {
_panel.onDraw(c);
}
} finally {
// do this in a finally so that if an exception is thrown
// during the above, we don't leave the Surface in an
// inconsistent state
if (c != null) {
_surfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
public void play() {
synchronized (_surfaceHolder) {
_panel.x = 10;
_panel.y = 10;
Log.i(TAG, "in Play");
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<com.example.opengl.GameView
android:id="#+id/gameView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/btnStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start" />
<Button
android:id="#+id/btnReset"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Reset" />
</LinearLayout>
</FrameLayout>