Add Edit-Text dynamically on Horizontal List View item - android

I am developing a photo editor app. Where I am giving an option of add text to image i.e writing some CAPTION or you can say TAG on that image. What I want is on "A"`s click, an Edit-Text should be added to the in image. Where can I insert name or any text.
What I want is describes in below image...
My code is below....
Second.java
package com.MyFirstApp.myfirstapp;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Calendar;
import java.util.Random;
import android.R.string;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.devsmart.android.ui.HorizontalListView;
public class Second extends Activity {
TouchImageView img_to_be_zoomedH, img_to_be_zoomed_secondH,
img_to_be_zoomedV, img_to_be_zoomed_secondV;
ImageView img_back, img_save;
HorizontalListView HListView, HListViewFirst, HListViewColor;
/* Save Parent Layout After Editing */
RelativeLayout parentLayoutforImgSaving;
Bitmap bitmap_img, bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
img_to_be_zoomedH = (TouchImageView) findViewById(R.id.img_to_be_zoomedH);
img_to_be_zoomed_secondH = (TouchImageView) findViewById(R.id.img_to_be_zoomed_secondH);
img_to_be_zoomedV = (TouchImageView) findViewById(R.id.img_to_be_zoomedV);
img_to_be_zoomed_secondV = (TouchImageView) findViewById(R.id.img_to_be_zoomed_secondV);
img_back = (ImageView) findViewById(R.id.img_back_icon);
img_save = (ImageView) findViewById(R.id.img_save_icon);
HListView = (HorizontalListView) findViewById(R.id.horizontal_list_view);
HListViewFirst = (HorizontalListView) findViewById(R.id.horizontal_list_view_first);
HListViewColor = (HorizontalListView) findViewById(R.id.horizontal_list_view_color);
parentLayoutforImgSaving = (RelativeLayout) findViewById(R.id.imagelayout);
/* Top Back Icon */
img_back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
/* Save Image Icon */
img_save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
saveImgAfterEditing(parentLayoutforImgSaving);
}
});
/* Left Image Touch Event */
img_to_be_zoomedH
.setOnTouchImageViewListener(new com.MyFirstApp.myfirstapp.TouchImageView.OnTouchImageViewListener() {
#Override
public void onMove() {
img_to_be_zoomed_secondH.setZoom(img_to_be_zoomedH);
PointF pointF_img1 = new PointF();
pointF_img1 = img_to_be_zoomedH.getScrollPosition();
img_to_be_zoomed_secondH.setScrollPosition(
1 - pointF_img1.x, pointF_img1.y);
}
});
/* Right Image touch event */
img_to_be_zoomed_secondH
.setOnTouchImageViewListener(new com.MyFirstApp.myfirstapp.TouchImageView.OnTouchImageViewListener() {
#Override
public void onMove() {
img_to_be_zoomedH.setZoom(img_to_be_zoomed_secondH);
PointF pointF_img1 = new PointF();
pointF_img1 = img_to_be_zoomed_secondH
.getScrollPosition();
img_to_be_zoomedH.setScrollPosition(1 - pointF_img1.x,
pointF_img1.y);
}
});
/* Top Image Touch Event */
img_to_be_zoomedV
.setOnTouchImageViewListener(new com.MyFirstApp.myfirstapp.TouchImageView.OnTouchImageViewListener() {
#Override
public void onMove() {
img_to_be_zoomed_secondV.setZoom(img_to_be_zoomedV);
PointF pointF_img1 = new PointF();
pointF_img1 = img_to_be_zoomedV.getScrollPosition();
img_to_be_zoomed_secondV.setScrollPosition(
pointF_img1.x, 1 - pointF_img1.y);
}
});
/* Bottom Image touch event */
img_to_be_zoomed_secondV
.setOnTouchImageViewListener(new com.MyFirstApp.myfirstapp.TouchImageView.OnTouchImageViewListener() {
#Override
public void onMove() {
img_to_be_zoomedV.setZoom(img_to_be_zoomed_secondV);
PointF pointF_img1 = new PointF();
pointF_img1 = img_to_be_zoomed_secondV
.getScrollPosition();
img_to_be_zoomedV.setScrollPosition(pointF_img1.x,
1 - pointF_img1.y);
}
});
int[] HorizontalListImages = new int[] { R.drawable.icon_grid,
R.drawable.icon_text, R.drawable.icon_clip_art };
final int[] HorizontalListImagesFirst = new int[] {
R.drawable.icon_go_back, R.drawable.icon_horizontal_grid,
R.drawable.icon_vertical_grid };
/* Animation References */
final Animation slideUp = AnimationUtils.loadAnimation(
getApplicationContext(), R.anim.slide_up);
final Animation slideDown = AnimationUtils.loadAnimation(
getApplicationContext(), R.anim.slide_down);
/* Setting Adapter for Horizontal List Views */
HorizontalListViewAdapter horizontalListViewAdapter = new HorizontalListViewAdapter(
Second.this, HorizontalListImages);
HListView.setAdapter(horizontalListViewAdapter);
/* Horizontal List View Item Click Listener */
HListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
switch (position) {
case 0:
HorizontalListViewAdapterFirst horizontalListViewAdapterFirst = new HorizontalListViewAdapterFirst(
Second.this, HorizontalListImagesFirst);
HListViewFirst.setAdapter(horizontalListViewAdapterFirst);
HListView.startAnimation(slideDown);
HListView.setVisibility(View.GONE);
HListViewFirst.startAnimation(slideUp);
HListViewFirst.setVisibility(View.VISIBLE);
break;
case 1:
/* Space for adding dynamic Edit-Text */
break;
default:
break;
}
}
});
HListViewFirst.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
/* HighLight Selected Option */
for (int i = 0; i < HListViewFirst.getChildCount(); i++) {
if (position == i) {
HListViewFirst.getChildAt(i).setBackgroundColor(
Color.GRAY);
} else {
HListViewFirst.getChildAt(i).setBackgroundColor(
Color.TRANSPARENT);
}
}
/* Get Device`s Height, Width */
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(
displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
switch (position) {
case 0:
HListViewFirst.startAnimation(slideDown);
HListViewFirst.setVisibility(View.GONE);
HListView.startAnimation(slideUp);
HListView.setVisibility(View.VISIBLE);
break;
case 1:
/* Setting Center Layout For Both Images */
RelativeLayout.LayoutParams ImagelayoutParams1 = new RelativeLayout.LayoutParams(
width, width);
ImagelayoutParams1.addRule(RelativeLayout.CENTER_IN_PARENT);
((RelativeLayout) findViewById(R.id.imagelayout))
.setLayoutParams(ImagelayoutParams1);
/* Setting Left ImageView width, height */
RelativeLayout.LayoutParams layoutParamsLeft = new RelativeLayout.LayoutParams(
width / 2, width);
layoutParamsLeft.setMargins(0, 0, 0, 0);
img_to_be_zoomedH.setLayoutParams(layoutParamsLeft);
img_to_be_zoomedH.setVisibility(view.VISIBLE);
bitmap_img = ((BitmapDrawable) img_to_be_zoomedH
.getDrawable()).getBitmap();
bitmap_img = flipImage(bitmap_img, 2);
img_to_be_zoomed_secondH.setImageBitmap(bitmap_img);
/* Setting Right ImageView width, height */
RelativeLayout.LayoutParams layoutParamsRight = new RelativeLayout.LayoutParams(
width / 2, width);
layoutParamsRight.setMargins(width / 2, 0, 0, 0);
img_to_be_zoomed_secondH.setLayoutParams(layoutParamsRight);
// img_to_be_zoomedH.invalidate();
img_to_be_zoomed_secondH.setVisibility(view.VISIBLE);
/* Hiding Vertical TouchIMageViews */
if ((img_to_be_zoomedV.getVisibility() == view.VISIBLE)
|| (img_to_be_zoomed_secondV.getVisibility() == view.VISIBLE)) {
img_to_be_zoomedV.setVisibility(view.GONE);
img_to_be_zoomed_secondV.setVisibility(view.GONE);
}
break;
case 2:
/* Setting Center Layout For Both Images */
RelativeLayout.LayoutParams ImagelayoutParams2 = new RelativeLayout.LayoutParams(
width, width);
ImagelayoutParams2.addRule(RelativeLayout.CENTER_IN_PARENT);
((RelativeLayout) findViewById(R.id.imagelayout))
.setLayoutParams(ImagelayoutParams2);
/* Setting Top ImageView width, height */
RelativeLayout.LayoutParams layoutParamsTop = new RelativeLayout.LayoutParams(
width, width / 2);
layoutParamsTop.setMargins(0, 0, 0, 0);
img_to_be_zoomedV.setLayoutParams(layoutParamsTop);
img_to_be_zoomedV.setVisibility(view.VISIBLE);
bitmap_img = ((BitmapDrawable) img_to_be_zoomedV
.getDrawable()).getBitmap();
bitmap_img = flipImage(bitmap_img, 1);
img_to_be_zoomed_secondV.setImageBitmap(bitmap_img);
/* Setting Bottom ImageView width, height */
RelativeLayout.LayoutParams layoutParamsBottom = new RelativeLayout.LayoutParams(
width, width / 2);
layoutParamsBottom.setMargins(0, width / 2, 0, 0);
img_to_be_zoomed_secondV
.setLayoutParams(layoutParamsBottom);
// img_to_be_zoomedV.invalidate();
img_to_be_zoomed_secondV.setVisibility(view.VISIBLE);
/* Hiding Horizontal TouchIMageViews */
if ((img_to_be_zoomedH.getVisibility() == view.VISIBLE)
|| (img_to_be_zoomed_secondH.getVisibility() == view.VISIBLE)) {
img_to_be_zoomedH.setVisibility(view.GONE);
img_to_be_zoomed_secondH.setVisibility(view.GONE);
}
break;
default:
break;
}
}
});
/* Getting ImageURI from Gallery from Main Activity */
Uri selectedImgUri = getIntent().getData();
if (selectedImgUri != null) {
String[] selectedImgPath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImgUri,
selectedImgPath, null, null, null);
cursor.moveToFirst();
int indexCol = cursor.getColumnIndex(selectedImgPath[0]);
String imgPath = cursor.getString(indexCol);
cursor.close();
img_to_be_zoomedH.setImageBitmap(BitmapFactory.decodeFile(imgPath));
img_to_be_zoomedV.setImageBitmap(BitmapFactory.decodeFile(imgPath));
}
/* Getting ImageBitmap from Camera from Main Activity */
Intent intent_camera = getIntent();
Bitmap camera_img_bitmap = (Bitmap) intent_camera
.getParcelableExtra("BitmapImage");
if (camera_img_bitmap != null) {
img_to_be_zoomedH.setImageBitmap(camera_img_bitmap);
img_to_be_zoomedV.setImageBitmap(camera_img_bitmap);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/* Flip Image Function */
public Bitmap flipImage(Bitmap src, int type) {
Matrix matrix = new Matrix();
/* Flip vertically */
if (type == 1) {
matrix.preScale(1.0f, -1.0f);
/* Flip horizontally */
} else if (type == 2) {
matrix.preScale(-1.0f, 1.0f);
} else {
return null;
}
return Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(),
matrix, true);
}
/* Save Image Function */
private void saveImgAfterEditing(RelativeLayout perent) {
try {
View content = parentLayoutforImgSaving;
content.setDrawingCacheEnabled(true);
content.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
Bitmap bitmap = content.getDrawingCache();
String extr = Environment.getExternalStorageDirectory().toString();
File mFolder = new File(extr + "/" + getString(R.string.app_name));
if (!mFolder.exists()) {
mFolder.mkdir();
}
Calendar c = Calendar.getInstance();
String s = getString(R.string.app_name) + c.getTimeInMillis()
+ ".png";
File f = new File(mFolder.getAbsolutePath(), s);
FileOutputStream fos = null;
fos = new FileOutputStream(f);
bitmap.compress(CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
bitmap.recycle();
Toast.makeText(getBaseContext(), "Image Saved", 5000).show();
addImageGallery(f);
} catch (Exception e) {
Toast.makeText(getBaseContext(), "Failed To Save", 5000).show();
e.printStackTrace();
}
}
/* Save Image to Direct Gallery, No Need to Refresh */
private void addImageGallery(File file) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
}
activity_second.java
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.MyFirstApp.myfirstapp.Second" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp" >
<ImageView
android:id="#+id/img_back_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:contentDescription="#string/img_back_icon"
android:src="#drawable/icon_back" />
<TextView
android:id="#+id/txtview_app_name_top"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="#string/txtview_app_name_top" />
<ImageView
android:id="#+id/img_save_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:contentDescription="#string/img_save_icon"
android:src="#drawable/icon_save" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/imagelayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" >
<com.MyFirstApp.myfirstapp.TouchImageView
android:id="#+id/img_to_be_zoomedH"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="23dp"
android:src="#drawable/home" >
</com.MyFirstApp.myfirstapp.TouchImageView>
<com.MyFirstApp.myfirstapp.TouchImageView
android:id="#+id/img_to_be_zoomed_secondH"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"
android:visibility="gone" >
</com.MyFirstApp.myfirstapp.TouchImageView>
<com.MyFirstApp.myfirstapp.TouchImageView
android:id="#+id/img_to_be_zoomedV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"
android:visibility="gone" >
</com.MyFirstApp.myfirstapp.TouchImageView>
<com.MyFirstApp.myfirstapp.TouchImageView
android:id="#+id/img_to_be_zoomed_secondV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"
android:visibility="gone" >
</com.MyFirstApp.myfirstapp.TouchImageView>
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" >
<com.devsmart.android.ui.HorizontalListView
android:id="#+id/horizontal_list_view"
android:layout_width="wrap_content"
android:layout_height="40dp" >
</com.devsmart.android.ui.HorizontalListView>
<com.devsmart.android.ui.HorizontalListView
android:id="#+id/horizontal_list_view_first"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:choiceMode="singleChoice"
android:listSelector="#drawable/horizontal_list_view_selector"
android:visibility="gone" >
</com.devsmart.android.ui.HorizontalListView>
<com.devsmart.android.ui.HorizontalListView
android:id="#+id/horizontal_list_view_color"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:visibility="gone" >
</com.devsmart.android.ui.HorizontalListView>
</RelativeLayout>
</RelativeLayout>
I want similar to below image...
Thanks in advance.

Related

Surface View and Linear layout and onClick event

I have a problem with adding my surface view to a linear layout, I have tried the already available answers and still cant seem to figure it out. My aim is to render an animation at the bottom of my login screen when my the next button is clicked. I tried adding a linear Layout to the Screen and then adding my gameView object on to that.
This is the loginActivity and game View Class for clarity I've also added the xml.
`package com.example.Combat;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.*;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
public GameView gameView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//setting the font
Typeface myTypeFace = Typeface.createFromAsset(getAssets(),"Typo Oxin free promo.ttf");
TextView myTextView = (TextView) findViewById(R.id.nameTextView);
myTextView.setTypeface(myTypeFace);
gameView = new GameView(this);
// LinearLayout.LayoutParams lp =new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
// lp.gravity= Gravity.BOTTOM;
LinearLayout myLayout = new LinearLayout(this);
myLayout.findViewById(R.id.gameLayoutView);
myLayout.addView(gameView);
}
#Override
public void onResume(){
super.onResume();
gameView.resume();
}
#Override
protected void onPause(){
super.onPause();
gameView.pause();
}
public void beginMotion(View view) {
GameView.isMoving=!GameView.isMoving;
// startActivity(new Intent(getApplicationContext(),transitionActivity.class));
}
}
`
package com.example.Combat;
import android.content.Context;
import android.graphics.*;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/**
* Created by vmuser on 2017/05/05.
*/
public class GameView extends SurfaceView implements Runnable{
private Thread gameThread;
private SurfaceHolder ourHolder;
public static volatile boolean playing=false;
private Canvas canvas;
private Bitmap bitmapRunningMan;
public static boolean isMoving=false;
private float runSpeedPerSecond = 150;
//LinearLayout screen=(LinearLayout)findViewById(R.id.theScreen);
private float manXPos = 1020, manYPos = 950;
private int frameWidth = 230, frameHeight = 274;
private int frameCount = 6;
private int currentFrame = 0;
private long fps;
private long timeThisFrame;
private long lastFrameChangeTime = 0;
private int frameLengthInMillisecond = 60;
private Rect frameToDraw = new Rect(0, 0, frameWidth, frameHeight);
private RectF whereToDraw = new RectF(manXPos, manYPos, manXPos + frameWidth, frameHeight);
public GameView(Context context) {
super(context);
ourHolder = getHolder();
bitmapRunningMan = BitmapFactory.decodeResource(getResources(),
R.drawable.perfectsoldier);
bitmapRunningMan = Bitmap.createScaledBitmap(bitmapRunningMan,
frameWidth * frameCount, frameHeight, false);
}
#Override
public void run() {
while (playing) {
long startFrameTime = System.currentTimeMillis();
update();
this.draw();
Log.d("theOne","its Happennig");
timeThisFrame = System.currentTimeMillis() - startFrameTime;
if (timeThisFrame >= 1) {
fps = 1000 / timeThisFrame;
}
}
}
public void update() {
if (isMoving) {
manXPos = manXPos - runSpeedPerSecond / fps;
if (manXPos > 0) {
//manYPos += (int) frameHeight;
//manXPos = 10;
isMoving=false;
}
if (manYPos + frameHeight > 0) {
// manYPos = 10;
isMoving=false;
}
}
}
public void manageCurrentFrame() {
long time = System.currentTimeMillis();
if (isMoving) {
if (time > lastFrameChangeTime + frameLengthInMillisecond) {
lastFrameChangeTime = time;
currentFrame++;
if (currentFrame >= frameCount) {
currentFrame = 0;
}
}
}
frameToDraw.left = currentFrame * frameWidth;
frameToDraw.right = frameToDraw.left + frameWidth;
}
public void draw() {
if (ourHolder.getSurface().isValid()) {
canvas = ourHolder.lockCanvas();
canvas.drawColor(Color.WHITE);
whereToDraw.set((int) manXPos, (int) manYPos, (int) manXPos
+ frameWidth, (int) manYPos + frameHeight);
manageCurrentFrame();
canvas.drawBitmap(bitmapRunningMan, frameToDraw, whereToDraw, null);
ourHolder.unlockCanvasAndPost(canvas);
}
}
public void pause() {
playing = false;
try {
gameThread.join();
} catch(InterruptedException e) {
Log.e("ERR", "Joining Thread");
}
}
public void resume() {
playing = true;
gameThread = new Thread(this);
gameThread.start();
}
// public boolean onTouchEvent(MotionEvent event) {
// switch (event.getActionMasked() & MotionEvent.ACTION_MASK) {
// case MotionEvent.ACTION_DOWN :
// isMoving = !isMoving;
// break;
// }
//
// return true;
// }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:focusableInTouchMode="true"
android:color="#000000"
android:weightSum="1" android:background="#ffffff" android:orientation="vertical"
android:id="#+id/theScreen">
<ImageView
android:layout_width="113dp"
android:layout_height="130dp"
android:src="#drawable/thelogo"
android:id="#+id/imageView" android:layout_gravity="center_horizontal"/>
<TextView
android:layout_width="145dp"
android:layout_height="49dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="combat"
android:textSize="30sp"
android:textColor="#000000"
android:id="#+id/nameTextView" android:layout_gravity="right" android:layout_weight="0.06"/>
<EditText
android:layout_width="270dp"
android:layout_height="wrap_content"
android:hint="Username"
android:textColorHint="#808080"
android:textColor="#22272a"
android:id="#+id/userNameEditText" android:layout_gravity="center_horizontal"/>
<Button
android:layout_width="261dp"
android:layout_height="wrap_content"
android:text="Next"
android:drawableRight="#drawable/thearrow"
android:textColor="#000000"
android:onClick="beginMotion"
android:id="#+id/NextButton" android:layout_gravity="center_horizontal" android:background="#638455"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Create an account"
android:id="#+id/textView" android:layout_gravity="center_horizontal" android:layout_weight="0.07"
android:textColor="#22272A"/>
<LinearLayout
android:id="#+id/gameLayoutView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
</LinearLayout>
</LinearLayout>
You haven't attached myLayout to the activity main layout that you earlier set on setContentView(R.layout.main).
Instead of:
LinearLayout myLayout = new LinearLayout(this);
myLayout.findViewById(R.id.gameLayoutView);
myLayout.addView(gameView);
You should write this:
LinearLayout myLayout = (LinearLayout) findViewById(R.id.gameLayoutView);
myLayout.addView(gameView);

TouchImageView zoom issue

I am developing a photo-editor app. I have done horizontally and vertically flipping. Now, The problem is that When I choose horizontally flip option and do zoom then choose vertically flip option and do zoom and then I choose horizontally flip option again, Than left TouchImageView is misplaced, but right TouchImageView is in place. Below images explains much better.....
Step-1: Choose image from Gallery....
Step-2: Flip it horizontally....
Step-3: Zoom in horizontal flip....
Step-4: Flip it vertically....
Step-5: Zoom in vertical flip....
Step-6: Now back to horizontal flip....
Now, see step no 3 & 6. Step no.6 must be same as step no.3
What I have done is below.
Second.java
package com.MyFirstApp.myfirstapp;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Calendar;
import java.util.Random;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.devsmart.android.ui.HorizontalListView;
public class Second extends Activity {
TouchImageView img_to_be_zoomedH, img_to_be_zoomed_secondH,
img_to_be_zoomedV, img_to_be_zoomed_secondV;
ImageView img_back, img_save;
HorizontalListView HListView, HListViewFirst;
/* Save Parent Layout After Editing */
RelativeLayout parentLayoutforImgSaving;
Bitmap bitmap_img, bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
img_to_be_zoomedH = (TouchImageView) findViewById(R.id.img_to_be_zoomedH);
img_to_be_zoomed_secondH = (TouchImageView) findViewById(R.id.img_to_be_zoomed_secondH);
img_to_be_zoomedV = (TouchImageView) findViewById(R.id.img_to_be_zoomedV);
img_to_be_zoomed_secondV = (TouchImageView) findViewById(R.id.img_to_be_zoomed_secondV);
img_back = (ImageView) findViewById(R.id.img_back_icon);
img_save = (ImageView) findViewById(R.id.img_save_icon);
HListView = (HorizontalListView) findViewById(R.id.horizontal_list_view);
HListViewFirst = (HorizontalListView) findViewById(R.id.horizontal_list_view_first);
parentLayoutforImgSaving = (RelativeLayout) findViewById(R.id.imagelayout);
/* Top Back Icon */
img_back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
/* Save Image Icon */
img_save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
saveImgAfterEditing(parentLayoutforImgSaving);
}
});
/* Left Image Touch Event */
img_to_be_zoomedH
.setOnTouchImageViewListener(new com.MyFirstApp.myfirstapp.TouchImageView.OnTouchImageViewListener() {
#Override
public void onMove() {
img_to_be_zoomed_secondH.setZoom(img_to_be_zoomedH);
PointF pointF_img1 = new PointF();
pointF_img1 = img_to_be_zoomedH.getScrollPosition();
img_to_be_zoomed_secondH.setScrollPosition(
1 - pointF_img1.x, pointF_img1.y);
}
});
/* Right Image touch event */
img_to_be_zoomed_secondH
.setOnTouchImageViewListener(new com.MyFirstApp.myfirstapp.TouchImageView.OnTouchImageViewListener() {
#Override
public void onMove() {
img_to_be_zoomedH.setZoom(img_to_be_zoomed_secondH);
PointF pointF_img1 = new PointF();
pointF_img1 = img_to_be_zoomed_secondH
.getScrollPosition();
img_to_be_zoomedH.setScrollPosition(1 - pointF_img1.x,
pointF_img1.y);
}
});
/* Top Image Touch Event */
img_to_be_zoomedV
.setOnTouchImageViewListener(new com.MyFirstApp.myfirstapp.TouchImageView.OnTouchImageViewListener() {
#Override
public void onMove() {
img_to_be_zoomed_secondV.setZoom(img_to_be_zoomedV);
PointF pointF_img1 = new PointF();
pointF_img1 = img_to_be_zoomedV.getScrollPosition();
img_to_be_zoomed_secondV.setScrollPosition(
pointF_img1.x, 1 - pointF_img1.y);
}
});
/* Bottom Image touch event */
img_to_be_zoomed_secondV
.setOnTouchImageViewListener(new com.MyFirstApp.myfirstapp.TouchImageView.OnTouchImageViewListener() {
#Override
public void onMove() {
img_to_be_zoomedV.setZoom(img_to_be_zoomed_secondV);
PointF pointF_img1 = new PointF();
pointF_img1 = img_to_be_zoomed_secondV
.getScrollPosition();
img_to_be_zoomedV.setScrollPosition(pointF_img1.x,
1 - pointF_img1.y);
}
});
int[] HorizontalListImages = new int[] { R.drawable.icon_grid,
R.drawable.icon_text, R.drawable.icon_clip_art };
final int[] HorizontalListImagesFirst = new int[] {
R.drawable.icon_go_back, R.drawable.icon_horizontal_grid,
R.drawable.icon_vertical_grid };
/* Animation References */
final Animation slideUp = AnimationUtils.loadAnimation(
getApplicationContext(), R.anim.slide_up);
final Animation slideDown = AnimationUtils.loadAnimation(
getApplicationContext(), R.anim.slide_down);
/* Setting Adapter for Horizontal List Views */
HorizontalListViewAdapter horizontalListViewAdapter = new HorizontalListViewAdapter(
Second.this, HorizontalListImages);
HListView.setAdapter(horizontalListViewAdapter);
/* Horizontal List View Item Click Listener */
HListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
switch (position) {
case 0:
HorizontalListViewAdapterFirst horizontalListViewAdapterFirst = new HorizontalListViewAdapterFirst(
Second.this, HorizontalListImagesFirst);
HListViewFirst.setAdapter(horizontalListViewAdapterFirst);
HListView.startAnimation(slideDown);
HListView.setVisibility(View.GONE);
HListViewFirst.startAnimation(slideUp);
HListViewFirst.setVisibility(View.VISIBLE);
break;
default:
break;
}
}
});
HListViewFirst.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
/* HighLight Selected Option */
for (int i = 0; i < HListViewFirst.getChildCount(); i++) {
if (position == i) {
HListViewFirst.getChildAt(i).setBackgroundColor(
Color.GRAY);
} else {
HListViewFirst.getChildAt(i).setBackgroundColor(
Color.TRANSPARENT);
}
}
/* Get Device`s Height, Width */
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(
displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
switch (position) {
case 0:
HListViewFirst.startAnimation(slideDown);
HListViewFirst.setVisibility(View.GONE);
HListView.startAnimation(slideUp);
HListView.setVisibility(View.VISIBLE);
break;
case 1:
/* Setting Center Layout For Both Images */
RelativeLayout.LayoutParams ImagelayoutParams1 = new RelativeLayout.LayoutParams(
width, width);
ImagelayoutParams1.addRule(RelativeLayout.CENTER_IN_PARENT);
((RelativeLayout) findViewById(R.id.imagelayout))
.setLayoutParams(ImagelayoutParams1);
/* Setting Left ImageView width, height */
RelativeLayout.LayoutParams layoutParamsLeft = new RelativeLayout.LayoutParams(
width / 2, width);
layoutParamsLeft.setMargins(0, 0, 0, 0);
img_to_be_zoomedH.setLayoutParams(layoutParamsLeft);
img_to_be_zoomedH.setVisibility(view.VISIBLE);
bitmap_img = ((BitmapDrawable) img_to_be_zoomedH
.getDrawable()).getBitmap();
bitmap_img = flipImage(bitmap_img, 2);
img_to_be_zoomed_secondH.setImageBitmap(bitmap_img);
/* Setting Right ImageView width, height */
RelativeLayout.LayoutParams layoutParamsRight = new RelativeLayout.LayoutParams(
width / 2, width);
layoutParamsRight.setMargins(width / 2, 0, 0, 0);
img_to_be_zoomed_secondH.setLayoutParams(layoutParamsRight);
// img_to_be_zoomedH.invalidate();
img_to_be_zoomed_secondH.setVisibility(view.VISIBLE);
/* Hiding Vertical TouchIMageViews */
if ((img_to_be_zoomedV.getVisibility() == view.VISIBLE)
|| (img_to_be_zoomed_secondV.getVisibility() == view.VISIBLE)) {
img_to_be_zoomedV.setVisibility(view.GONE);
img_to_be_zoomed_secondV.setVisibility(view.GONE);
}
break;
case 2:
/* Setting Center Layout For Both Images */
RelativeLayout.LayoutParams ImagelayoutParams2 = new RelativeLayout.LayoutParams(
width, width);
ImagelayoutParams2.addRule(RelativeLayout.CENTER_IN_PARENT);
((RelativeLayout) findViewById(R.id.imagelayout))
.setLayoutParams(ImagelayoutParams2);
/* Setting Top ImageView width, height */
RelativeLayout.LayoutParams layoutParamsTop = new RelativeLayout.LayoutParams(
width, width / 2);
layoutParamsTop.setMargins(0, 0, 0, 0);
img_to_be_zoomedV.setLayoutParams(layoutParamsTop);
img_to_be_zoomedV.setVisibility(view.VISIBLE);
bitmap_img = ((BitmapDrawable) img_to_be_zoomedV
.getDrawable()).getBitmap();
bitmap_img = flipImage(bitmap_img, 1);
img_to_be_zoomed_secondV.setImageBitmap(bitmap_img);
/* Setting Bottom ImageView width, height */
RelativeLayout.LayoutParams layoutParamsBottom = new RelativeLayout.LayoutParams(
width, width / 2);
layoutParamsBottom.setMargins(0, width / 2, 0, 0);
img_to_be_zoomed_secondV
.setLayoutParams(layoutParamsBottom);
// img_to_be_zoomedV.invalidate();
img_to_be_zoomed_secondV.setVisibility(view.VISIBLE);
/* Hiding Horizontal TouchIMageViews */
if ((img_to_be_zoomedH.getVisibility() == view.VISIBLE)
|| (img_to_be_zoomed_secondH.getVisibility() == view.VISIBLE)) {
img_to_be_zoomedH.setVisibility(view.GONE);
img_to_be_zoomed_secondH.setVisibility(view.GONE);
}
break;
default:
break;
}
}
});
/* Getting ImageURI from Gallery from Main Activity */
Uri selectedImgUri = getIntent().getData();
if (selectedImgUri != null) {
String[] selectedImgPath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImgUri,
selectedImgPath, null, null, null);
cursor.moveToFirst();
int indexCol = cursor.getColumnIndex(selectedImgPath[0]);
String imgPath = cursor.getString(indexCol);
cursor.close();
img_to_be_zoomedH.setImageBitmap(BitmapFactory.decodeFile(imgPath));
img_to_be_zoomedV.setImageBitmap(BitmapFactory.decodeFile(imgPath));
}
/* Getting ImageBitmap from Camera from Main Activity */
Intent intent_camera = getIntent();
Bitmap camera_img_bitmap = (Bitmap) intent_camera
.getParcelableExtra("BitmapImage");
if (camera_img_bitmap != null) {
img_to_be_zoomedH.setImageBitmap(camera_img_bitmap);
img_to_be_zoomedV.setImageBitmap(camera_img_bitmap);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/* Flip Image Function */
public Bitmap flipImage(Bitmap src, int type) {
Matrix matrix = new Matrix();
/* Flip vertically */
if (type == 1) {
matrix.preScale(1.0f, -1.0f);
/* Flip horizontally */
} else if (type == 2) {
matrix.preScale(-1.0f, 1.0f);
} else {
return null;
}
return Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(),
matrix, true);
}
/* Save Image Function */
private void saveImgAfterEditing(RelativeLayout perent) {
try {
View content = parentLayoutforImgSaving;
content.setDrawingCacheEnabled(true);
content.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
Bitmap bitmap = content.getDrawingCache();
String extr = Environment.getExternalStorageDirectory().toString();
File mFolder = new File(extr + "/" + getString(R.string.app_name));
if (!mFolder.exists()) {
mFolder.mkdir();
}
Calendar c = Calendar.getInstance();
String s = getString(R.string.app_name) + c.getTimeInMillis()
+ ".png";
File f = new File(mFolder.getAbsolutePath(), s);
FileOutputStream fos = null;
fos = new FileOutputStream(f);
bitmap.compress(CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
bitmap.recycle();
Toast.makeText(getBaseContext(), "Image Saved", 5000).show();
addImageGallery(f);
} catch (Exception e) {
Toast.makeText(getBaseContext(), "Failed To Save", 5000).show();
e.printStackTrace();
}
}
/* Save Image to Direct Gallery, No Need to Refresh */
private void addImageGallery(File file) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
}
activity_second.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.MyFirstApp.myfirstapp.Second" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp" >
<ImageView
android:id="#+id/img_back_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:contentDescription="#string/img_back_icon"
android:src="#drawable/icon_back" />
<TextView
android:id="#+id/txtview_app_name_top"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="#string/txtview_app_name_top" />
<ImageView
android:id="#+id/img_save_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:contentDescription="#string/img_save_icon"
android:src="#drawable/icon_save" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/imagelayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" >
<com.MyFirstApp.myfirstapp.TouchImageView
android:id="#+id/img_to_be_zoomedH"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="23dp"
android:src="#drawable/home" >
</com.MyFirstApp.myfirstapp.TouchImageView>
<com.MyFirstApp.myfirstapp.TouchImageView
android:id="#+id/img_to_be_zoomed_secondH"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"
android:visibility="gone" >
</com.MyFirstApp.myfirstapp.TouchImageView>
<com.MyFirstApp.myfirstapp.TouchImageView
android:id="#+id/img_to_be_zoomedV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"
android:visibility="gone" >
</com.MyFirstApp.myfirstapp.TouchImageView>
<com.MyFirstApp.myfirstapp.TouchImageView
android:id="#+id/img_to_be_zoomed_secondV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"
android:visibility="gone" >
</com.MyFirstApp.myfirstapp.TouchImageView>
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" >
<com.devsmart.android.ui.HorizontalListView
android:id="#+id/horizontal_list_view"
android:layout_width="wrap_content"
android:layout_height="40dp" >
</com.devsmart.android.ui.HorizontalListView>
<com.devsmart.android.ui.HorizontalListView
android:id="#+id/horizontal_list_view_first"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:choiceMode="singleChoice"
android:listSelector="#drawable/horizontal_list_view_selector"
android:visibility="gone" >
</com.devsmart.android.ui.HorizontalListView>
</RelativeLayout>
</RelativeLayout>
Thanks in advance.

Converting Activity to use Fragments?

I basically have an activity that has tabs. I want it so that when I select a different tab the fragment at the bottom changes to the selected tab. I know that theres 2 ways to do it. 1 is reload the same grid view with new data. I want it so that I can switch between tabs and it loads all the grid views as you left them. Is this possible and how can I modify this code to support that:
MainActivity:
package com.td.flickrsearch;
import java.util.ArrayList;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver;
import android.view.animation.DecelerateInterpolator;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.td.flickrsearch.entity.FlickrPhoto;
import com.td.flickrsearch.image.ImageCache.ImageCacheParams;
import com.td.flickrsearch.image.ImageFetcher;
public class MainActivity extends FragmentActivity implements OnClickListener, TabListener {
private int mImageThumbSize;
private int mImageThumbSpacing;
private ImageFetcher mImageFetcher;
public static int currentPage = 1;
private boolean endOfAlbums = false;
private int lastItem = 0;
private TextView tvNoAlbums;
private ProgressBar progressLoadMore;
GridView albumGrid;
ImageAdapter imageAdapter;
ArrayList<FlickrPhoto> _feed = new ArrayList<FlickrPhoto>();
ProgressDialog progressDialog;
private Handler myHandler = new Handler();
private Runnable updateRunnable;
EditText etSearch;
Button btnSearch;
private Animator mCurrentAnimator;
private int mShortAnimationDuration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_fragment);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// For each of the sections in the app, add a tab to the action bar.
actionBar.addTab(actionBar.newTab().setText("Friends").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Chat").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Me").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Users").setTabListener(this));
//actionBar.addTab(actionBar.newTab().setText(R.string.title_section3).setTabListener(this));
// Set the Animation time form the android defaults
mShortAnimationDuration = getResources().getInteger(android.R.integer.config_shortAnimTime);
// ////////////////////////////////////////
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Fetching images, please wait...");
progressDialog.setCancelable(false);
// ////////////////////////////////////////
// /////////////////////////////////////////
etSearch = (EditText) findViewById(R.id.etSearch);
btnSearch = (Button) findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(this);
// /////////////////////////////////////////
mImageThumbSize = getResources().getDimensionPixelSize(R.dimen.photo_thumbnail_size);
mImageThumbSpacing = getResources().getDimensionPixelSize(R.dimen.photo_thumbnail_spacing);
// ////////////////////////////////////////////
ImageCacheParams cacheParams = new ImageCacheParams(this, Util.IMAGE_CACHE_DIR);
// The ImageFetcher takes care of loading images into our ImageView
// children asynchronously
mImageFetcher = new ImageFetcher(this, mImageThumbSize);
mImageFetcher.setLoadingImage(R.drawable.empty_photo);
mImageFetcher.addImageCache(this.getSupportFragmentManager(), cacheParams);
// ////////////////////////////////////////////
progressLoadMore = (ProgressBar) findViewById(R.id.progress);
progressLoadMore.setVisibility(View.GONE);
// //////////////////////////////////////////////S
imageAdapter = new ImageAdapter();
albumGrid = (GridView) findViewById(R.id.photoGrid);
tvNoAlbums = (TextView) findViewById(R.id.tvNoAlbums);
albumGrid.setAdapter(imageAdapter);
albumGrid.setFastScrollEnabled(true);
// This listener is used to get the final width of the GridView and then
// calculate the
// number of columns and the width of each column. The width of each
// column is variable
// as the GridView has stretchMode=columnWidth. The column width is used
// to set the height
// of each view so we get nice square thumbnails.
albumGrid.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (imageAdapter.getNumColumns() == 0) {
final int numColumns = (int) Math.floor(albumGrid.getWidth() / (mImageThumbSize + mImageThumbSpacing));
if (numColumns > 0) {
final int columnWidth = (albumGrid.getWidth() / numColumns) - mImageThumbSpacing;
imageAdapter.setNumColumns(numColumns);
imageAdapter.setItemHeight(columnWidth);
}
}
}
});
// albumGrid on item click:
albumGrid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int pos, long arg3) {
// On click
// Display the zoomed in image in full screen
zoomImageFromThumb(v, pos);
}
});
albumGrid.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int scrollState) {
// Pause fetcher to ensure smoother scrolling when flinging
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) {
mImageFetcher.setPauseWork(true);
} else {
mImageFetcher.setPauseWork(false);
}
}
#Override
public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
final int _lastItem = firstVisibleItem + visibleItemCount;
if (_lastItem > 0 && totalItemCount > 0)
if (_lastItem == _feed.size() && !endOfAlbums && lastItem != _lastItem) {
lastItem = _lastItem;
// Last item is fully visible.
loadAlbums(etSearch.getText().toString().trim());
}
}
});
etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
_feed.clear();
currentPage = 1;
Util.hideSoftKeyboard(MainActivity.this);
loadAlbums(etSearch.getText().toString().trim());
return true;
}
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_search:
// search action
Toast.makeText(this, "Search selected", Toast.LENGTH_SHORT)
.show();
return true;
case R.id.action_help:
// help action
Toast.makeText(this, "help selected", Toast.LENGTH_SHORT)
.show();
return true;
case R.id.action_refresh:
// refresh
Toast.makeText(this, "refresh selected", Toast.LENGTH_SHORT)
.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSearch:
// perform search
_feed.clear();
currentPage = 1;
Util.hideSoftKeyboard(MainActivity.this);
loadAlbums(etSearch.getText().toString().trim().replaceAll(" ", ""));
break;
default:
break;
}
}
private void loadAlbums(final String tag) {
if (currentPage == 1) {
_feed.clear();
endOfAlbums = false;
lastItem = 0;
// get new photos
progressDialog.show();
} else
progressLoadMore.setVisibility(View.VISIBLE);
if (Util.isNetworkAvailable(MainActivity.this)) {
new Thread(new Runnable() {
#Override
public void run() {
ArrayList<FlickrPhoto> serverAlbums;
// get the serverAlbums
serverAlbums = FlickrParser.getPhotos(tag, currentPage);
if (serverAlbums.size() > 0)
_feed.addAll(serverAlbums);
else
endOfAlbums = true;
currentPage++;
myHandler.post(updateRunnable);
}
}).start();
updateRunnable = new Runnable() {
#Override
public void run() {
if (_feed.size() > 0) {
imageAdapter.notifyDataSetChanged();
// get listview current position - used to maintain
// scroll position
int currentPosition = albumGrid.getFirstVisiblePosition();
// Setting new scroll position
albumGrid.smoothScrollToPosition(currentPosition + 1, 0);
} else
tvNoAlbums.setVisibility(View.VISIBLE);
progressDialog.dismiss();
progressLoadMore.setVisibility(View.GONE);
}
};
} else {
Toast.makeText(this, R.string.check_connectivity, Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
progressLoadMore.setVisibility(View.GONE);
}
}
// ///////////////////////////Zoom in Image///////////////////////////////
private void zoomImageFromThumb(final View thumbView, int pos) {
// If there's an animation in progress, cancel it immediately and
// proceed with this one.
if (mCurrentAnimator != null) {
mCurrentAnimator.cancel();
}
// Load the high-resolution "zoomed-in" image.
final ImageView expandedImageView = (ImageView) findViewById(R.id.expanded_image);
// mImageFetcher.loadImage(Util.getPhotoUrlLarge(_feed.get(pos)),
// expandedImageView);
mImageFetcher.loadImage(Util.getPhotoUrl(_feed.get(pos)), expandedImageView);
// Calculate the starting and ending bounds for the zoomed-in image.
// This step
// involves lots of math. Yay, math.
final Rect startBounds = new Rect();
final Rect finalBounds = new Rect();
final Point globalOffset = new Point();
// The start bounds are the global visible rectangle of the thumbnail,
// and the
// final bounds are the global visible rectangle of the container view.
// Also
// set the container view's offset as the origin for the bounds, since
// that's
// the origin for the positioning animation properties (X, Y).
thumbView.getGlobalVisibleRect(startBounds);
findViewById(R.id.container).getGlobalVisibleRect(finalBounds, globalOffset);
startBounds.offset(-globalOffset.x, -globalOffset.y);
finalBounds.offset(-globalOffset.x, -globalOffset.y);
// Adjust the start bounds to be the same aspect ratio as the final
// bounds using the
// "center crop" technique. This prevents undesirable stretching during
// the animation.
// Also calculate the start scaling factor (the end scaling factor is
// always 1.0).
float startScale;
if ((float) finalBounds.width() / finalBounds.height() > (float) startBounds.width() / startBounds.height()) {
// Extend start bounds horizontally
startScale = (float) startBounds.height() / finalBounds.height();
float startWidth = startScale * finalBounds.width();
float deltaWidth = (startWidth - startBounds.width()) / 2;
startBounds.left -= deltaWidth;
startBounds.right += deltaWidth;
} else {
// Extend start bounds vertically
startScale = (float) startBounds.width() / finalBounds.width();
float startHeight = startScale * finalBounds.height();
float deltaHeight = (startHeight - startBounds.height()) / 2;
startBounds.top -= deltaHeight;
startBounds.bottom += deltaHeight;
}
// Hide the thumbnail and show the zoomed-in view. When the animation
// begins,
// it will position the zoomed-in view in the place of the thumbnail.
thumbView.setAlpha(0f);
expandedImageView.setVisibility(View.VISIBLE);
// Set the pivot point for SCALE_X and SCALE_Y transformations to the
// top-left corner of
// the zoomed-in view (the default is the center of the view).
expandedImageView.setPivotX(0f);
expandedImageView.setPivotY(0f);
// Construct and run the parallel animation of the four translation and
// scale properties
// (X, Y, SCALE_X, and SCALE_Y).
AnimatorSet set = new AnimatorSet();
set.play(ObjectAnimator.ofFloat(expandedImageView, View.X, startBounds.left, finalBounds.left))
.with(ObjectAnimator.ofFloat(expandedImageView, View.Y, startBounds.top, finalBounds.top))
.with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_X, startScale, 1f))
.with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_Y, startScale, 1f));
set.setDuration(mShortAnimationDuration);
set.setInterpolator(new DecelerateInterpolator());
set.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mCurrentAnimator = null;
}
#Override
public void onAnimationCancel(Animator animation) {
mCurrentAnimator = null;
}
});
set.start();
mCurrentAnimator = set;
// Upon clicking the zoomed-in image, it should zoom back down to the
// original bounds
// and show the thumbnail instead of the expanded image.
final float startScaleFinal = startScale;
expandedImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mCurrentAnimator != null) {
mCurrentAnimator.cancel();
}
// Animate the four positioning/sizing properties in parallel,
// back to their
// original values.
AnimatorSet set = new AnimatorSet();
set.play(ObjectAnimator.ofFloat(expandedImageView, View.X, startBounds.left))
.with(ObjectAnimator.ofFloat(expandedImageView, View.Y, startBounds.top))
.with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_X, startScaleFinal))
.with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_Y, startScaleFinal));
set.setDuration(mShortAnimationDuration);
set.setInterpolator(new DecelerateInterpolator());
set.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
thumbView.setAlpha(1f);
expandedImageView.setVisibility(View.GONE);
mCurrentAnimator = null;
}
#Override
public void onAnimationCancel(Animator animation) {
thumbView.setAlpha(1f);
expandedImageView.setVisibility(View.GONE);
mCurrentAnimator = null;
}
});
set.start();
mCurrentAnimator = set;
}
});
}
// //////////////////////////////////////////////////////////
// ///////////////// ADAPTER ////////////////////////////////
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private int mItemHeight = 0;
private int mNumColumns = 0;
private RelativeLayout.LayoutParams mImageViewLayoutParams;
public ImageAdapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mImageViewLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
}
public int getCount() {
return _feed.size();
}
public void setNumColumns(int numColumns) {
mNumColumns = numColumns;
}
public int getNumColumns() {
return mNumColumns;
}
public void setItemHeight(int height) {
if (height == mItemHeight) {
return;
}
mItemHeight = height;
mImageViewLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, mItemHeight);
notifyDataSetChanged();
}
public FlickrPhoto getItem(int position) {
return _feed.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = mInflater.inflate(R.layout.grid_item, null);
holder.cover = (ImageView) view.findViewById(R.id.cover);
holder.title = (TextView) view.findViewById(R.id.title);
view.setTag(holder);
} else
holder = (ViewHolder) view.getTag();
holder.cover.setLayoutParams(mImageViewLayoutParams);
// Check the height matches our calculated column width
if (holder.cover.getLayoutParams().height != mItemHeight) {
holder.cover.setLayoutParams(mImageViewLayoutParams);
}
FlickrPhoto photo = getItem(position);
mImageFetcher.loadImage(Util.getPhotoUrl(photo), holder.cover);
holder.cover.setScaleType(ImageView.ScaleType.CENTER_CROP);
holder.title.setText(photo.getTitle());
return view;
}
}
class ViewHolder {
ImageView cover;
TextView title;
}
#Override
public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
// TODO Auto-generated method stub
if (tab.getPosition() == 0) {
}
else if (tab.getPosition() == 1) {
}
else {
//AndroidVersionList androidversionlist = new AndroidVersionList();
//getSupportFragmentManager().beginTransaction().replace(R.id.container, androidversionlist).commit();
/*Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, tab.getPosition() + 1);
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();*/
}
}
#Override
public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
ActivityMain.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" />
ListFragment.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:id="#+id/llSearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dp" >
<EditText
android:id="#+id/etSearch"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:layout_weight="9"
android:drawableRight="#drawable/edit_search"
android:hint="tag name"
android:imeOptions="actionSearch"
android:inputType="textNoSuggestions"
android:singleLine="true" />
<Button
android:id="#+id/btnSearch"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_marginTop="2dp"
android:layout_weight="2"
android:text="Go!" />
</LinearLayout>
<GridView
android:id="#+id/photoGrid"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/progress"
android:layout_below="#+id/llSearch"
android:alwaysDrawnWithCache="true"
android:clipChildren="true"
android:columnWidth="#dimen/photo_thumbnail_size"
android:fadeScrollbars="false"
android:fastScrollEnabled="true"
android:horizontalSpacing="#dimen/photo_thumbnail_spacing"
android:numColumns="auto_fit"
android:padding="6dp"
android:scrollbars="none"
android:scrollingCache="true"
android:smoothScrollbar="true"
android:stretchMode="columnWidth"
android:verticalSpacing="#dimen/photo_thumbnail_spacing" />
<ProgressBar
android:id="#+id/progress"
style="#android:style/Widget.ProgressBar.Large"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="4dp"
android:padding="10dp" />
<TextView
android:id="#+id/tvNoAlbums"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="No photos to display!"
android:textSize="14sp"
android:textStyle="bold"
android:visibility="gone" />
<ImageView
android:id="#+id/expanded_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="#string/app_name"
android:visibility="invisible" />
</RelativeLayout>
Right now I think the best way to do it is probably separate the adapter, make this into separate fragments. Would I be able to switch back to the fragment and will it be in the state I left it in?
So for example if a user scrolled down in the gridview when I switch back to the fragment will it be at the same position with the same data?
It would be great if you could help me convert this into something that will do that. I dont really know much about it so all help is really appreciated. Thank You :)
I would suggest that:
when you do your fragment transactions, remember to add the fragment to the backstack public abstract FragmentTransaction addToBackStack (String name) so that you can find the fragment later instead of having the garbage collector destroy your fragment.
When you add your fragment to the backstack, it will do :
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
.... Save whatever else is uniqe about your fragment here
}
When you go back to your fragment, since you added it to the backstack, use :
onViewStateRestored()
Called when all saved state has been restored into the view hierarchy of the fragment.
This can be used to do initialization based on saved state that you are letting the view
hierarchy track itself, such as whether check box widgets are currently checked. This is
called after onActivityCreated(Bundle) and before onStart().

Adding drawable image to background of canvas

I know its possible to paint the background of canvas using
mPaint = new Paint();
mPaint.setColor(Color.RED);
Im just wondering how to i set a permanent background for it. Ive tried using the xml file but nothing happens. Any ideas?
This is the source code of the project, ive been following a tutorial how to do it because im fairly unfamiliar with bitmaps.
Canvas Class
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
public class GameBoard extends View{
private int mFlagX = -1;
private int mFlagY = -1;
private Bitmap mBitmap = null;
private Bitmap nBitmap = null;
private Paint mPaint = null;
private boolean isFlagHidden = false;
private int mBoundX = -1;
private int mBoundY = -1;
//play with these values to make the app more or less challenging
public final int CLOSER = 50;
public final int CLOSE = 100;
public GameBoard(Context context, AttributeSet aSet) {
super(context, aSet);
//load our bitmap
mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.star);
//create a paint brush
mPaint = new Paint();
mPaint.setColor(Color.RED);
}
#Override
public void onDraw(Canvas canvas) {
//initialize
if ((mFlagX < 1) || (mFlagY < 1)) {
mFlagX = (int) (getWidth() / 2) - mBitmap.getWidth() / 2;
mFlagY = (int) (getHeight() / 2) - mBitmap.getHeight() / 2;
mBoundX = (int)getWidth() - mBitmap.getWidth();
mBoundY = (int)getHeight() - mBitmap.getHeight();
}
//draw background
canvas.drawRect(0, 0, getWidth(), getHeight(), mPaint);
//draw the flag
if (!isFlagHidden) {
canvas.drawBitmap(mBitmap, mFlagX, mFlagY, null);
}
}
public void hideTheFlag(){
//randomize flag location
mFlagX = (int) Math.ceil(Math.random() * mBoundX);
mFlagY = (int) Math.ceil(Math.random() * mBoundY);
isFlagHidden = true;
//force redraw
invalidate();
}
public void giveUp(){
isFlagHidden = false;
//force redraw
invalidate();
}
public Indicators takeAGuess(float x, float y) {
//this is our "warm" area
Rect prettyClose = new Rect(mFlagX - CLOSE, mFlagY - CLOSE, mFlagX+mBitmap.getWidth() + CLOSE, mFlagY+mBitmap.getHeight() + CLOSE);
//normalize
if (prettyClose.left < 0) prettyClose.left = 0;
if (prettyClose.top < 0) prettyClose.top = 0;
if (prettyClose.right > mBoundX) prettyClose.right = mBoundX;
if (prettyClose.bottom > mBoundY) prettyClose.bottom = mBoundY;
//this is our "hot" area
Rect reallyClose = new Rect(mFlagX - CLOSER, mFlagY - CLOSER, mFlagX+mBitmap.getWidth() + CLOSER, mFlagY+mBitmap.getHeight() + CLOSER);
//normalize
if (reallyClose.left < 0) reallyClose.left = 0;
if (reallyClose.top < 0) reallyClose.top = 0;
if (reallyClose.right > mBoundX) reallyClose.right = mBoundX;
if (reallyClose.bottom > mBoundY) reallyClose.bottom = mBoundY;
//this is the area that contains our flag
Rect bullsEye = new Rect(mFlagX, mFlagY, mFlagX+mBitmap.getWidth(), mFlagY+mBitmap.getHeight());
//check to see where on the board the user pressed
if (bullsEye.contains((int) x, (int)y)) {
//found it
isFlagHidden = false;
invalidate();
return Indicators.BULLSEYE;
} else if (reallyClose.contains((int) x, (int)y)) {
//hot
return Indicators.HOT;
} else if (prettyClose.contains((int)x, (int)y)) {
//warm
return Indicators.WARM;
} else {
//not even close
return Indicators.COLD;
}
}
}
Game Class
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.TextView;
public class FindTheStar extends Activity implements OnTouchListener, OnClickListener{
private GameBoard mGameBoard = null;
private boolean isFlagHidden = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_star);
mGameBoard = (GameBoard) findViewById(R.id.Hide_canvas);
mGameBoard.setOnTouchListener(this);
Button b = (Button) findViewById(R.id.the_button);
b.setOnClickListener(this);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (v.getId() == R.id.Hide_canvas) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (isFlagHidden) {
TextView tv = (TextView)findViewById (R.id.the_label);
switch (mGameBoard.takeAGuess(event.getX(), event.getY())) {
case BULLSEYE:
Button b = (Button) findViewById(R.id.the_button);
isFlagHidden = false;
b.setText("Go Hide!");
tv.setText("You found me!");
tv.setTextColor(Color.GREEN);
break;
case HOT:
tv.setText("You're hot!");
tv.setTextColor(Color.RED);
break;
case WARM:
tv.setText("Getting warm...");
tv.setTextColor(Color.YELLOW);
break;
case COLD:
tv.setText("You're cold.");
tv.setTextColor(Color.BLUE);
break;
}
}
}
return true;
}
return false;
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.the_button) {
TextView tv = (TextView)findViewById (R.id.the_label);
tv.setText("");
Button b = (Button) findViewById(R.id.the_button);
isFlagHidden = !isFlagHidden;
if (isFlagHidden) {
b.setText("Can't find me?");
mGameBoard.hideTheFlag();
} else {
b.setText("Go Hide!");
mGameBoard.giveUp();
}
}
}
}
XML File
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/the_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:textSize="20sp"
android:layout_marginBottom="10dip"
android:text="Lets Play Hide and Seek!"/>
<Button
android:id="#+id/the_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:layout_marginBottom="10dip"
android:text="Go Hide!"/>
<app.autismapp.GameBoard
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/Hide_canvas"/>
</LinearLayout>
yes you can set your permanent background using xml layout..i done this by creating two class.
this is my code in MainACtivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final BrushView view=new BrushView(this);
setContentView(R.layout.mylayout);//removed this one if the paint doesnt work
view.setBackgroundResource(R.drawable.background);//to set background
setContentView(view);// to display the background
and my second class
public class PaintView extends View {
private Paint paint = new Paint();
public LayoutParams params;
public PaintView(Context context) {
super(context);
paint.setAntiAlias(true);
paint.setColor(Color.BLUE);
i hope it gives you an idea

How to Hide and Show Buttons on Alternate Touch Events

My activity displays images and i want to display two buttons when the user touch the screen, and to disappear these button on next touch.
My activity file ImageViewPager.java is as follows:
package com.pankajvatsa.testfeet;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class ImageViewPager extends Activity {
// Declare Variable
int position;
Button bWallpaperButton;
Button bDownloadButton;
RelativeLayout mainLay;
int flagForButton = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set title for the ViewPager
setTitle("ViewPager");
// Get the view from view_pager.xml
setContentView(R.layout.activity_image_view_pager);
mainLay = (RelativeLayout) findViewById(R.id.rl_view_pager);
mainLay.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == MotionEvent.ACTION_DOWN) {
bWallpaperButton.setVisibility(View.VISIBLE);
bDownloadButton.setVisibility(View.VISIBLE);
return true;
}
if (event.getAction() == MotionEvent.ACTION_UP) {
bWallpaperButton.setVisibility(View.INVISIBLE);
bDownloadButton.setVisibility(View.INVISIBLE);
return true;
}
return true;
}
});
bWallpaperButton = (Button) findViewById(R.id.bSetWallpaper);
bDownloadButton = (Button) findViewById(R.id.bSaveToGallery);
// Retrieve data from MainActivity on item click event
Intent p = getIntent();
position = p.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
List<ImageView> images = new ArrayList<ImageView>();
// Retrieve all the images
for (int i = 0; i < imageAdapter.getCount(); i++) {
ImageView imageView = new ImageView(this);
imageView.setImageResource(imageAdapter.mThumbIds[i]);
imageView.setScaleType(ImageView.ScaleType.CENTER);
images.add(imageView);
}
// Set the images into ViewPager
ImagePagerAdapter pageradapter = new ImagePagerAdapter(images);
ViewPager viewpager = (ViewPager) findViewById(R.id.image_pager);
viewpager.setAdapter(pageradapter);
// Show images following the position
viewpager.setCurrentItem(position);
}
}
And my xml file is as follows:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rl_view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true" >
<android.support.v4.view.ViewPager
android:id="#+id/image_pager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true" >
</android.support.v4.view.ViewPager>
<Button
android:id="#+id/bSetWallpaper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="#string/set_wallpaper"
android:visibility="gone" />
<Button
android:id="#+id/bSaveToGallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:text="#string/save_local"
android:visibility="gone" />
</RelativeLayout>
Here is an example using LinearLayout but should work fine with RelativeLayout as well:
Button btn1;
boolean gone = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button)findViewById(R.id.button1);
LinearLayout ln = (LinearLayout)findViewById(R.id.LinearLayout01);
ln.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if(motionEvent.getAction() == MotionEvent.ACTION_DOWN){
if(!gone){
btn1.setVisibility(View.GONE);
gone = true;
}else{
btn1.setVisibility(View.VISIBLE);
gone = false;
}
}
return true;
}
});
}
Well, it somehow worked on removing the setOnTouchListener() from layout and adding it on the ViewPager.
My Updated code(with other changes for differentiating tap and swipe) is:
package com.pankajvatsa.testfeet;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class ImageViewPager extends Activity {
// Declare Variable
int position;
Button bWallpaperButton;
Button bDownloadButton;
RelativeLayout mainLay;
int flagForButton = 0;
boolean gone = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set title for the ViewPager
setTitle("ViewPager");
// Get the view from view_pager.xml
setContentView(R.layout.activity_image_view_pager);
bWallpaperButton = (Button) findViewById(R.id.bSetWallpaper);
bDownloadButton = (Button) findViewById(R.id.bSaveToGallery);
mainLay = (RelativeLayout) findViewById(R.id.rl_view_pager);
// Retrieve data from MainActivity on item click event
Intent p = getIntent();
position = p.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
List<ImageView> images = new ArrayList<ImageView>();
// Retrieve all the images
for (int i = 0; i < imageAdapter.getCount(); i++) {
ImageView imageView = new ImageView(this);
imageView.setImageResource(imageAdapter.mThumbIds[i]);
imageView.setScaleType(ImageView.ScaleType.CENTER);
images.add(imageView);
}
// Set the images into ViewPager
ImagePagerAdapter pageradapter = new ImagePagerAdapter(images);
ViewPager viewpager = (ViewPager) findViewById(R.id.image_pager);
viewpager.setAdapter(pageradapter);
// Show images following the position
viewpager.setCurrentItem(position);
viewpager.setOnTouchListener(new View.OnTouchListener() {
private float pointX;
private float pointY;
private int tolerance = 50;
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
return false;
case MotionEvent.ACTION_DOWN:
pointX = event.getX();
pointY = event.getY();
break;
case MotionEvent.ACTION_UP:
boolean sameX = pointX + tolerance > event.getX() && pointX - tolerance < event.getX();
boolean sameY = pointY + tolerance > event.getY() && pointY - tolerance < event.getY();
if(sameX && sameY){
//The user "clicked" certain point in the screen or just returned to the same position an raised the finger
if(gone == false){
bWallpaperButton.setVisibility(View.GONE);
bDownloadButton.setVisibility(View.GONE);
gone = true;
}else{
bWallpaperButton.setVisibility(View.VISIBLE);
bDownloadButton.setVisibility(View.VISIBLE);
gone = false;
}
}
}
return false;
}
});
}
}

Categories

Resources