Drag and drop JLabel while preserving the original JLabel - jlabel

I am working on a GUI that displays an image of a floor plan (JLabel with ImageIcon) and a number of small icons (JLabels with ImageIcon) down the left hand side. The idea is to be able to select one of the icons and drag and drop it onto a position on the floor plan. My code is working fine except that when you drag an icon onto the floor plan, I need the original icon to remain in place, so it can be placed in several other positions on the floor plan if required. So I need to be able to clone the icon that I am moving when the mouse is pressed.
My code below shows a temp fix between the //******** markers but of course this only works correctly for the topmost icon. I need to somehow clone "Component comp" as a new JLabel.
Below is the relevant part of my code:
class MouseHandler extends MouseAdapter {
private Component dragComponent;
private Sidebar board;
private Point dragOffset;
public MouseHandler(Sidebar board) {
this.board = board;
}
public Sidebar getBoard() {
return board;
}
#Override
public void mousePressed(MouseEvent e) {
Component comp = getBoard().getComponentAt(e.getPoint());
if (comp != null) {
if (comp instanceof JLabel) {
//**************
String imagePath = "/Downlight 1.gif";
Image Images = new ImageIcon(this.getClass().getResource(imagePath)).getImage();
String path = "Images" + imagePath;
ImageIcon icon = new ImageIcon(path);
JLabel lbl = new JLabel(icon);
lbl.setBounds(22, 26, 36, 36);
lbl.setIcon(new ImageIcon(Images));
lbl.setOpaque(true);
Sidebar board = getBoard();
board.add(lbl, new Point(40, 44));
board.setComponentZOrder(lbl, 0);
//**************
dragComponent = comp;
dragOffset = new Point();
dragOffset.x = e.getPoint().x - comp.getX();
dragOffset.y = e.getPoint().y - comp.getY();
}
}
}
#Override
public void mouseDragged(MouseEvent e) {
if (dragComponent != null) {
board = getBoard();
Point dragPoint = new Point();
dragPoint.x = e.getPoint().x - dragOffset.x;
dragPoint.y = e.getPoint().y - dragOffset.y;
dragComponent.setLocation(dragPoint);
}
}
#Override
public void mouseReleased(MouseEvent e) {
if (dragComponent != null) {
dragComponent = null;
}
}
}
}
Thanks in advance for any help with this.

I found a solution that enabled me to copy the icon and bounds of the original JLabel to a new JLabel, which replaces the one being dragged:
#Override
public void mousePressed(MouseEvent e) {
Component comp = getBoard().getComponentAt(e.getPoint());
if (comp != null) {
if (comp instanceof JLabel) {
JLabel label = (JLabel) comp;
ImageIcon icon = ((ImageIcon)label.getIcon());
Rectangle rect = label.getBounds();
JLabel lbl = new JLabel(icon);
lbl.setBounds(rect);
lbl.setVisible(true);;
lbl.setOpaque(true);
Mainpanel board = getBoard();
board.add(lbl);
board.setComponentZOrder(lbl, 0);
dragComponent = comp;
dragOffset = new Point();
dragOffset.x = e.getPoint().x - comp.getX();
dragOffset.y = e.getPoint().y - comp.getY();
}
}
}

Related

AVCaptureSession captured photo's size different than the preview?

EDIT:: Reading through this again now realize it isn’t very clear as to how the pictures were captured, how they’re being displayed, and why/what makes them different.
To that end— We are using AVCapture library to manually take photos within our app. We have a preview display in the app so the user can see what the image they’re taking looks like, just how any standard photo app these days does it. So what these two images are showing are the preview of the image on the screen, before the image is captured and the captured image. This was done by taking a screenshot of the preview and then a screenshot of the resulting capture image.
All this to say the captured image appears to be returned with differing dimensions or scaling attributes. We are displaying the preview and the resulting captures using a native iOS preview view and a Xamarin.Image respectively.
Below details our attempts at addressing the issue by changing sizing, layering, and stretching attributes to no avail.
To that end we’ve created a support ticket with MSFT regarding this issue.
These two images are the camera preview and the resulting capture (in that order, respectively [taken via screenshots]). We want the captured photo to match the preview/vice versa. How can we address this?
Tried manipulating the CALayer containing the photo data to size the image like how a Xamarin.Forms' image sizes with AspectFit by assigning the ContentsGravity with various options like kCAGravityResizeAspect. Fiddled with other Contents options such as ContentsRect and ContentsScale but no dice. Below is the View and its corresponding Renderer. So how to address the sizing issue?
Native Camera View
namespace App.iOS.Views
{
public class NativeCameraView : UIView
{
AVCaptureVideoPreviewLayer previewLayer;
CameraOptions cameraOptions;
public AVCaptureSession CaptureSession { get; private set; }
public AVCaptureStillImageOutput CaptureOutput { get; set; }
public bool IsPreviewing { get; set; }
public NativeCameraPreview(CameraOptions options)
{
cameraOptions = options;
IsPreviewing = false;
Initialize();
}
public override void LayoutSubviews()
{
base.LayoutSubviews();
UIDevice device = UIDevice.CurrentDevice;
UIDeviceOrientation orientation = device.Orientation;
AVCaptureConnection previewLayerConnection = this.previewLayer.Connection;
if (previewLayerConnection.SupportsVideoOrientation)
{
switch (orientation)
{
case UIDeviceOrientation.Portrait:
UpdatePreviewLayer(previewLayerConnection,
AVCaptureVideoOrientation.Portrait);
break;
case UIDeviceOrientation.LandscapeRight:
UpdatePreviewLayer(previewLayerConnection,
AVCaptureVideoOrientation.LandscapeLeft);
break;
case UIDeviceOrientation.LandscapeLeft:
UpdatePreviewLayer(previewLayerConnection,
AVCaptureVideoOrientation.LandscapeRight);
break;
case UIDeviceOrientation.PortraitUpsideDown:
UpdatePreviewLayer(previewLayerConnection,
AVCaptureVideoOrientation.PortraitUpsideDown);
break;
default:
UpdatePreviewLayer(previewLayerConnection,
AVCaptureVideoOrientation.Portrait);
break;
}
}
}
private void UpdatePreviewLayer(AVCaptureConnection layer,
AVCaptureVideoOrientation orientation)
{
layer.VideoOrientation = orientation;
previewLayer.Frame = this.Bounds;
}
public async Task CapturePhoto()
{
var videoConnection = CaptureOutput.ConnectionFromMediaType(AVMediaType.Video);
var sampleBuffer = await CaptureOutput.CaptureStillImageTaskAsync(videoConnection);
var jpegData = AVCaptureStillImageOutput.JpegStillToNSData(sampleBuffer);
var photo = new UIImage(jpegData);
var rotatedPhoto = RotateImage(photo, 180f);
CALayer layer = new CALayer
{
//ContentsGravity = "kCAGravityResizeAspect",
//ContentsRect = rect,
//GeometryFlipped = true,
ContentsScale = 1.0f,
Frame = Bounds,
Contents = rotatedPhoto.CGImage //Contents = photo.CGImage,
};
MainPage.UpdateSource(UIImageFromLayer(layer).AsJPEG().AsStream());
MainPage.UpdateImage(UIImageFromLayer(layer).AsJPEG().AsStream());
}
public UIImage RotateImage(UIImage image, float degree)
{
float Radians = degree * (float)Math.PI / 180;
UIView view = new UIView(frame: new CGRect(0, 0, image.Size.Width, image.Size.Height));
CGAffineTransform t = CGAffineTransform.MakeRotation(Radians);
view.Transform = t;
CGSize size = view.Frame.Size;
UIGraphics.BeginImageContext(size);
CGContext context = UIGraphics.GetCurrentContext();
context.TranslateCTM(size.Width / 2, size.Height / 2);
context.RotateCTM(Radians);
context.ScaleCTM(1, -1);
context.DrawImage(new CGRect(-image.Size.Width / 2, -image.Size.Height / 2, image.Size.Width, image.Size.Height), image.CGImage);
UIImage imageCopy = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return imageCopy;
}
UIImage ImageFromLayer(CALayer layer)
{
UIGraphics.BeginImageContextWithOptions(
layer.Frame.Size,
layer.Opaque,
0);
layer.RenderInContext(UIGraphics.GetCurrentContext());
var outputImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return outputImage;
}
void Initialize()
{
CaptureSession = new AVCaptureSession();
CaptureSession.SessionPreset = AVCaptureSession.PresetPhoto;
previewLayer = new AVCaptureVideoPreviewLayer(CaptureSession)
{
Frame = Bounds,
VideoGravity = AVLayerVideoGravity.ResizeAspectFill
};
var videoDevices = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video);
var cameraPosition = (cameraOptions == CameraOptions.Front) ? AVCaptureDevicePosition.Front : AVCaptureDevicePosition.Back;
var device = videoDevices.FirstOrDefault(d => d.Position == cameraPosition);
if (device == null)
{
return;
}
NSError error;
var input = new AVCaptureDeviceInput(device, out error);
var dictionary = new NSMutableDictionary();
dictionary[AVVideo.CodecKey] = new NSNumber((int)AVVideoCodec.JPEG);
CaptureOutput = new AVCaptureStillImageOutput()
{
OutputSettings = new NSDictionary()
};
CaptureSession.AddOutput(CaptureOutput);
CaptureSession.AddInput(input);
Layer.AddSublayer(previewLayer);
CaptureSession.StartRunning();
IsPreviewing = true;
}
}
}
Native Camera Renderer
[assembly: ExportRenderer(typeof(CameraView), typeof(CameraViewRenderer))]
namespace App.iOS.Renderers
{
public class CameraViewRenderer : ViewRenderer<CameraView, NativeCameraView>
{
NativeCameraView uiCameraView;
protected override void OnElementChanged(ElementChangedEventArgs<CameraView> e)
{
base.OnElementChanged(e);
if (Control == null)
{
uiCameraView = new NativeCameraView(e.NewElement.Camera);
SetNativeControl(uiCameraView);
}
if (e.OldElement != null)
{
// Unsubscribe
uiCameraView.Tapped -= OnCameraViewTapped;
}
if (e.NewElement != null)
{
// Subscribe
uiCameraView.Tapped += OnCameraViewTapped;
}
}
async void OnCameraViewTapped(object sender, EventArgs e)
{
await uiCameraView.CapturePhoto();
}
}
}
NOTE A similar question appears to have been asked quite some time ago.

How to animate a filled triangle (drawn by a path) in Android Studio

I'm trying to build a jigsaw-like app for Android that involves the user moving polygonal pieces around the screen by touch event.
I can draw - for example - a triangle, and fill it. I can also move it smoothly round the screen but it leaves a trace - so that the screen rapidly fills up :-(
So I am wondering how to adjust the onDraw method so that the previous positions of the triangle are not included. Or is there some other technique? The question has been asked once before but did not get a satisfactory answer. I am quite new to Android work so I am sure a kind expert will be able to point me in the right direction!
The view:
public class GameView extends View {
public Triangle T1;
Paint paint = new Paint();
private Path path;
public GameView(Context context) {
super(context);
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.GREEN);
initTriangle();
}
public void initTriangle() {
int T1Points[][] = new int[3][2];
T1Points[0][0] = -200;
T1Points[0][1] = -100;
T1Points[1][0] = 200;
T1Points[1][1] = -100;
T1Points[2][0] = 0;
T1Points[2][1] = 100;
float[] position = new float[2];
position[0] = (float) 200.0;
position[1] = (float) 100.0;
T1 = new Triangle("T1", T1Points, position);
path = T1.getPath();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float[] pos = new float[2];
pos[0] = event.getX(); //nextx;
pos[1] = event.getY(); //nexty;
T1.setPosition(pos );
Path path = new Path();
path = T1.getPath();
postInvalidate();
return true;
}
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
}
}
Triangle class:
public class Triangle {
public int[][] myPoints;
public Path path;
public String myname;
public float[] position;
public Triangle (String name, int[][] newpoints, float[] posn) {
myPoints = new int[4][2];
int i;
for (i = 0; i < 3; i++) {
myPoints[i][0] = newpoints[i][0];
myPoints[i][1] = newpoints[i][1];
}
myPoints[3][0] = newpoints[0][0]; // closed circuit for future needs
myPoints[3][1] = newpoints[0][1];
path = new Path();
position = new float[2];
position[0] = posn[0];
position[1] = posn[1];
myname = name;
updatePath();
}
public void setPosition(float[] newPosition){
position[0] = newPosition[0];
position[1] = newPosition[1];
updatePath();
}
public void updatePath(){
int startx = myPoints[0][0] + Math.round(position[0]);
int starty = myPoints[0][1] + Math.round(position[1]);
path.moveTo(startx,starty);
for (int i = 1; i < myPoints.length; i++)
{
int newx = myPoints[i][0] + Math.round(position[0]);
int newy = myPoints[i][1] + Math.round(position[1]);
path.lineTo(newx,newy);
}
path.close();
}
public Path getPath() {
return path;
}
}
Main Activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uk.mydomain.animatedtriangle.GameView gameView = new uk.mydomain.animatedtriangle.GameView(this);
RelativeLayout relativeLayout = new RelativeLayout(this);
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT);
relativeLayout.setLayoutParams(relativeParams);
setContentView(relativeLayout);
relativeLayout.addView(gameView);
}
Sorted! Just needed to add a path.reset() at the end of onDraw.

screenshot of specific layout that is nested in main layout

I want to take a screen shot of a layout that is nested (in between) main layout. I'm using following code:
public static Bitmap captureScreen(View v) {
Bitmap bitmap = null;
try {
if (v != null) {
int width = v.getWidth();
int height = v.getHeight();
screenshot = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
v.draw(new Canvas(screenshot));
}
} catch (Exception e) {
Log.d("captureScreen", "Failed");
}
return bitmap;
}
on button click it would be like :
captureScreen(midlayout);

Moving an ImageView located in a WindowManager doesn't work properly

I'm trying to draw an Icon over everything on the screen (TOP MOST) similar to the chathead of new Facebook messenger
I have create a service to work in the background and based on a specific condition my icon should appear on the screen (exactly like when someone sends you a message on facebook the messenger service will hook the message and shows the chathead on the screen to notify you about the new message)
What I did:
I have created the service and gave it the permission to show system alert windows (since the head is actually a system alert window)
[assembly: UsesPermission(Name = Android.Manifest.Permission.SystemAlertWindow)]
I have inherited a class (StickyHeadView) from ImageView and implemented OnTouchListener listener using the following way :
class StickyHeadView : ImageView, Android.Views.View.IOnTouchListener
{
private StickyHeadService OwnerService;
public StickyHeadView(StickyHeadService ContextService, Context context)
: base(context)
{
OwnerService = ContextService;
SetOnTouchListener(this);
}
float TouchMoveX;
float TouchMoveY;
public bool OnTouch(View v, MotionEvent e)
{
var windowService = OwnerService.GetSystemService(Android.Content.Context.WindowService);
var windowManager = windowService.JavaCast<Android.Views.IWindowManager>();
switch (e.Action & e.ActionMasked)
{
case MotionEventActions.Move:
TouchMoveX = (int)e.GetX();
TouchMoveY = (int)e.GetY();
OwnerService.LOParams.X = (int)(TouchMoveX);
OwnerService.LOParams.Y = (int)(TouchMoveY);
windowManager.UpdateViewLayout(this, OwnerService.LOParams);
Log.Debug("Point : ", "X: " + Convert.ToString(OwnerService.LOParams.X) + " Y: " + Convert.ToString(OwnerService.LOParams.Y));
return true;
case MotionEventActions.Down:
return true;
case MotionEventActions.Up:
return true;
}
return false;
}
}
The service has wiindow manager to show the Icon on it...in Service "OnStart" event I initialize the Head :
private StickyHeadView MyHead;
public Android.Views.WindowManagerLayoutParams LOParams;
public override void OnStart(Android.Content.Intent intent, int startId)
{
base.OnStart(intent, startId);
var windowService = this.GetSystemService(Android.Content.Context.WindowService);
var windowManager = windowService.JavaCast<Android.Views.IWindowManager>();
MyHead = new StickyHeadView(this, this);
MyHead.SetImageResource(Resource.Drawable.Icon);
LOParams = new Android.Views.WindowManagerLayoutParams(Android.Views.WindowManagerLayoutParams.WrapContent,
Android.Views.WindowManagerLayoutParams.WrapContent,
Android.Views.WindowManagerTypes.Phone,
Android.Views.WindowManagerFlags.NotFocusable,
Android.Graphics.Format.Translucent);
LOParams.Gravity = GravityFlags.Top | GravityFlags.Left;
LOParams.X = 10;
LOParams.Y = 10;
windowManager.AddView(MyHead, LOParams);
}
as you can see I have declared a WindowManager and added the view (MyHead) to it with special parameters
My Problem :
When ever I try to move the View (My head) it doesn't move in a stable way and keeps having a quake!
I'm testing it using android 4.0.4 on real HTC Phone
I'm using monodroid
Please help...if the implementation of the touch is not right please suggest a better way...thank you.
In your code just use...
TYPE_SYSTEM_ALERT
or
TYPE_PHONE
instead of
TYPE_SYSTEM_OVERLAY
Hope this will help you.
a working example:
#Override
public void onCreate() {
super.onCreate();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
chatHead = new ImageView(this);
chatHead.setImageResource(R.drawable.ic_launcher);
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, //TYPE_PHONE
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.LEFT;
params.x = 0;
params.y = 100;
windowManager.addView(chatHead, params);
chatHead.setOnTouchListener(new View.OnTouchListener() {
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;
#Override public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
initialX = params.x;
initialY = params.y;
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
return true;
case MotionEvent.ACTION_UP:
return true;
case MotionEvent.ACTION_MOVE:
params.x = initialX + (int) (event.getRawX() - initialTouchX);
params.y = initialY + (int) (event.getRawY() - initialTouchY);
windowManager.updateViewLayout(chatHead, params);
return true;
}
return false;
}
});
}
The e.GetX()/eGetY() you are using is relative to view position so when you move the view with UpdateViewLayout the next values will be relative to the move. It works using GetRawX()/GetRawY(), but you have to keep track of the initial Down rawX and rawY also.
Here is my JAVA that works:
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
layoutParams.x = Math.round(event.getRawX() - downX);
layoutParams.y = Math.round(event.getRawY() - downY);
windowManager.updateViewLayout(floatingView, layoutParams);
return true;
case MotionEvent.ACTION_DOWN:
downX = event.getRawX() - layoutParams.x;
downY = event.getRawY() - layoutParams.y;
return true;
case MotionEvent.ACTION_UP:
return true;
}
return false;
}
One comment, there's a big downside in using windowManager.updateViewLayout(...) this method will call onLayout on the floating view for each move, and that might be a performance issue, anyway until now I haven't found another method to move the floating view.
Try this might be help ful
first add global variable on your activity:
WindowManager wm;
LinearLayout lay;
float downX,downY;
after put in code to oncreate on your activity
Button btnstart=(Button)findViewById(R.id.button1);
Button btnstop=(Button)findViewById(R.id.button2);
btnstart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(lay==null)
{
wm = (WindowManager) getApplicationContext().getSystemService(
Context.WINDOW_SERVICE);
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
| WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.x = (int) wm.getDefaultDisplay().getWidth();
params.y = 0;
// params.height = wm.getDefaultDisplay().getHeight()/2;
params.width = LayoutParams.WRAP_CONTENT;
params.format = PixelFormat.TRANSLUCENT;
params.gravity = Gravity.TOP | Gravity.LEFT;
params.setTitle("Info");
lay = null;
lay = new LinearLayout(getApplicationContext());
lay.setOrientation(LinearLayout.VERTICAL);
// lay.setAlpha(0.5f);
TextView txt_no = new TextView(getApplicationContext());
txt_no.setTextSize(10.0f);
txt_no.setText("Moving view by stack user!");
txt_no.setTextColor(Color.BLACK);
// txt_no.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
// LayoutParams.WRAP_CONTENT));
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(0, 0, 0, 0); // margins as you wish
txt_no.setGravity(Gravity.RIGHT);
txt_no.setBackgroundColor(Color.WHITE);
txt_no.setLayoutParams(layoutParams);
txt_no.setPadding(10, 10, 10, 10);
lay.addView(txt_no);
AlphaAnimation alpha = new AlphaAnimation(0.5F, 0.5F);
alpha.setDuration(0); // Make animation instant
alpha.setFillAfter(true); // Tell it to persist after the animation ends
// And then on your layout
wm.addView(lay, params);
txt_no.startAnimation(alpha);
downX=params.x;
downY=params.y;
Log.v("MSES>", "x="+ downX +",y="+ downY);
lay.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
params.x = Math.round(event.getRawX() - downX);
params.y = Math.round(event.getRawY() - downY);
wm.updateViewLayout(lay, params);
Log.v("MSES EVENT>", "x="+ event.getRawX() +",y="+ event.getRawY());
Log.v("MSES MOVE>", "x="+ params.x +",y="+ params.y);
return true;
case MotionEvent.ACTION_DOWN:
downX = event.getRawX() - params.x;
downY = event.getRawY() - params.y;
Log.v("MSES DOWN>", "x="+ params.x +",y="+ params.y);
return true;
case MotionEvent.ACTION_UP:
//params.x = Math.round(event.getRawX() - downX);
//params.y = Math.round(event.getRawY() - downY);
//wm.updateViewLayout(lay, params);
return true;
}
return false;
}
});
}
}
});
btnstop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (lay != null) {
lay.removeAllViews();
wm.removeViewImmediate(lay);
lay = null;
}
}
});

OnClickListener not working for first item in GridView inside ViewPager

Inside ViewPager, there is a gridview which has a grid of single choice answers with textviews and images. When i clicked on any answer, the textview should change its color to RED else WHITE. Its working fine for all the other answers except the first one. When i first clicked on first answer in gridview, it doesn't change the color, on second click it turns to RED, but then when i change the option, the RED color doesn't change to WHITE for first option. Look at the screen below,
Sorry Screen submission is not allowed for me as i am a new user...
Inside GridFragment#OnActivityCreated():
gridview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long arg3) {
currentPage = new TestTopics().getCuttentPage();
tv = ((ViewHolder) v.getTag()).lbl;
if(selectedValues.containsKey(currentPage))
{
selectedValues.get(currentPage).setTextColor(Color.WHITE);
selectedValues.remove(currentPage);
selectedValues.put(currentPage, tv);
selectedValues.get(currentPage).setTextColor(Color.RED);
}
else
{
selectedValues.put(currentPage, tv);
selectedValues.get(currentPage).setTextColor(Color.RED);
}
}
});
ImageAdapter#getView() method:
public View getView(int position, View convertView, ViewGroup parent) {
numTopics = mTopicList.getNumTopics ();
ViewHolder holder;
holder = new ViewHolder();
if (convertView == null) {
int layoutId = R.layout.demo_pager_grid_item;
LayoutInflater li = ((Activity) mContext).getLayoutInflater();
childView = li.inflate (layoutId, null);
holder.img = (ImageView) childView.findViewById(R.id.image);
holder.lbl = (TextView) childView.findViewById(R.id.title);
childView.setTag(holder);
} else {
childView = convertView;
holder = (ViewHolder) childView.getTag();
}
if (childView != null) {
// Set the width and height of the child view.
childView.setLayoutParams(new GridView.LayoutParams(mCellWidth, mCellHeight));
int j = position + mImageOffset;
if (j < 0) j = 0;
if (j >= numTopics) j = numTopics - 1;
imageView = (ImageView) childView.findViewById (R.id.image);
if (imageView != null) {
Resources res = mContext.getResources ();
int imagePadding = res.getDimensionPixelSize (R.dimen.grid_image_padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setBackgroundResource (R.color.background_grid1_cell);
imageView.setPadding (imagePadding, imagePadding, imagePadding, imagePadding);
imageView.setImageBitmap (mTopicList.getTopicImage (j));
imageView.setTag (new Integer (j));
}
textView = (TextView) childView.findViewById (R.id.title);
if (textView != null)
{
textView.setText(mTopicList.getTopicTitle (j));
textView.setTag (mTopicList.getTopicTitle (j));
holder.lbl.setTag(mTopicList.getTopicTitle (j));
}
}
return childView;
}
I have seen this link : OnClickListener not working for first item in GridView, and follow the answer, but didn't get succeed on it...
Where I'm going wrong?
Answered in a question edit. Converted to a community wiki answer. See What is the appropriate action when the answer to a question is added to the question itself? )
The OP wrote:
have solved it....
I added gridview.setBackgroundColor(Color.TRANSPARENT); in my following code :
if(patternItems.containsKey(currentPage) && selectedValues.containsKey(currentPage))
{
selectedValues.get(currentPage).setTextColor(Color.WHITE);
selectedValues.remove(currentPage);
selectedValues.put(currentPage, tv);
selectedValues.get(currentPage).setTextColor(Color.RED);
**gridview.setBackgroundColor(Color.TRANSPARENT);**
patternItems.remove(currentPage);
patternItems.put(currentPage,tv.getText().toString());
}
else
{
selectedValues.put(currentPage, tv);
selectedValues.get(currentPage).setTextColor(Color.RED);
**gridview.setBackgroundColor(Color.TRANSPARENT);**
patternItems.put(currentPage,tv.getText().toString());
}

Resources