Adding multiple image views programmatically - android

I'm basically trying to achieve drag&drop feature..
What i'm trying is that i provides sequence of images on the screen, if i click on any image available in images row that will be added to the Mains screen. But i'm getting problem that when i add new view into the Main Screen then all the other views also moved to top left corner.
Can you please tell me what is the problem...? Or kindly suggest me a tutorial or link where i can find solution.... or how to achieve this ?
I'm using Framelayout, So that i also achieve images overlapping...
This is the class in which all code is working:
public class drag extends Activity implements OnClickListener, OnTouchListener
{
ImageView img1;
Button btn,btn2;
FrameLayout layout;
LayoutParams params;
ImageView im , im2, im3 ,im4;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
layout = (FrameLayout) findViewById(R.id.vg);
layout.setDrawingCacheEnabled(true);
im = (ImageView)findViewById(R.id.img1);
im.setDrawingCacheEnabled(true);
im.setOnTouchListener(this);
im.setOnClickListener(this);
btn = (Button)findViewById(R.id.btn1);
btn.setDrawingCacheEnabled(true);
btn.setOnClickListener(this);
btn.setOnTouchListener(this);
btn2 = (Button)findViewById(R.id.btn2);
btn2.setDrawingCacheEnabled(true);
btn2.setOnClickListener(this);
btn2.setOnTouchListener(this);
params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
btn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
im2 = new ImageView(drag.this);
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.image);
im2.setImageBitmap(bm);
im2.setOnTouchListener(drag.this);
im2.setOnClickListener(drag.this);
layout.addView(im2, params);
}
});
btn2.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.image);
saveImage(bm);
}
});
}
public void saveImage(Bitmap myBitmap)
{
MediaStore.Images.Media.insertImage(getContentResolver(), myBitmap, "mmsImage" , "mmsimage");
}
int l, t, r, b;
int oldLeft, oldTop;
PointF p, curr;
#Override
public boolean onTouch(View view, MotionEvent me)
{
if (me.getAction() == MotionEvent.ACTION_DOWN)
{
//status = START_DRAGGING;
Log.i("status"," AAA dOWN");
img1 = new ImageView(this);
view.setDrawingCacheEnabled(true);
Bitmap mmsImage = Bitmap.createBitmap(view.getDrawingCache());
img1.setImageBitmap(mmsImage);
img1.setOnTouchListener(drag.this);
img1.setOnClickListener(drag.this);
oldLeft = (int)view.getLeft();
oldTop = (int)view.getTop();
p = new PointF(me.getRawX(), me.getRawY());
}
if (me.getAction() == MotionEvent.ACTION_MOVE)
{
Log.i("status"," AAA draging");
int xDiff = (int)(me.getRawX() - p.x);
int yDiff = (int)(me.getRawY() - p.y);
p.x = me.getRawX();
p.y = me.getRawY();
l = view.getLeft();
t = view.getTop();
r = view.getRight();
b = view.getBottom();
view.layout(l + xDiff, t + yDiff , r + xDiff, b + yDiff);
}
if (me.getAction() == MotionEvent.ACTION_UP)
{
Log.i("status"," AAA UP");
//captureUserMove(view);
}
return false;
}
}
Here is the XML :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/vg"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#android:color/white" >
<ImageView
android:id="#+id/img1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="#drawable/ic_launcher" />
<Button
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
<Button
android:id="#+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom" />
</FrameLayout>

You set params, but don't specify how to position the added view. Try this:
In onCreate()
params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.LEFT | Gravity.TOP; // you need this for margins to work
In the click listener:
// your x and y where you want the new view
params.leftMargin = x;
params.topMargin = y;

Putting
params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
inside
#Override
public void onClick(View v)
{
}
will work.

Related

Custom pop up dialog with imageview dragable android

I've followed this tutorial http://android-er.blogspot.co.id/2014/01/implement-drag-and-drop-movable.html with some modification. I want to show image on it and make the pop up draggable.
now it's work. but the problem is the image can not move to the corner of the screen. can anyone give me a solution about this issue? any suggestion would be appreciated
this my layout
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rootView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:id="#+id/imgResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/dismiss"
android:paddingTop="16dp"
android:text="close"/>
</LinearLayout>
and this my activity class
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button btnOpenPopup = (Button) findViewById(R.id.openpopup);
btnOpenPopup.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
LayoutInflater layoutInflater =
(LayoutInflater)getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
final PopupWindow popupWindow = new PopupWindow(
popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button btnDismiss = (Button)popupView.findViewById(R.id.dismiss);
ImageView imageView = (ImageView) popupView.findViewById(R.id.imgResult);
int imageResource = getResources().getIdentifier("#drawable/toy", null, getPackageName());
Drawable res = getResources().getDrawable(imageResource);
imageView.setImageDrawable(res);
btnDismiss.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
popupWindow.dismiss();
}});
popupWindow.showAsDropDown(btnOpenPopup, 50, -30);
popupView.setOnTouchListener(new OnTouchListener() {
int orgX, orgY;
int offsetX, offsetY;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
orgX = (int) event.getX();
orgY = (int) event.getY();
break;
case MotionEvent.ACTION_MOVE:
offsetX = (int)event.getRawX() - orgX;
offsetY = (int)event.getRawY() - orgY;
popupWindow.update(offsetX, offsetY, -1, -1, true);
break;
}
return true;
}});
}
});
}
}

Is there an easy way to check if two ImageViews collide?

I tried that:
if (pic_runner.getX() + pic_runner.getY() == pic_a.getX() + pic_a.getY()){
Toast.makeText(getApplicationContext(), "KOLLIDIERT!", Toast.LENGTH_SHORT).show();
}
But that didn't work.
And I tried the same with && operators, but then I get the error "Operator '&&' cannot be applied to 'float', 'boolean'"
To check the collision of two ImageViews, you could do something like this:
{
ImageView pic1 = (ImageView) findViewById(R.id.pic1);
ImageView pic2 = (ImageView) findViewById(R.id.pic2);
Rect pic1Rect = new Rect();
Rect pic2Rect = new Rect();
pic1.getDrawingRect(pic1Rect);
pic2.getDrawingRect(pic2Rect);
Log.e("TEST", "hasCollision: " + hasCollision(pic1Rect, pic2Rect));
}
public static boolean hasCollision(Rect one, Rect two) {
return (one.left < two.right &&
one.right > two.left &&
one.top < two.bottom &&
one.bottom > two.top);
}
EDIT
public class MainActivity extends AppCompatActivity {
private ImageView pic1;
private ImageView pic2;
private Rect pic1Rect = new Rect();
private Rect pic2Rect = new Rect();
private boolean collisionEventHandled = false;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pic1 = (ImageView) findViewById(R.id.pic1);
pic2 = (ImageView) findViewById(R.id.pic2);
RelativeLayout main = (RelativeLayout) findViewById(R.id.main);
Button btn = (Button) findViewById(R.id.button);
main.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
pic2.setX(event.getX());
pic2.setY(event.getY());
return true;
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pic1Rect.left = (int) pic1.getX();
pic1Rect.top = (int) pic1.getY();
pic1Rect.right = (int) pic1.getX() + pic1.getWidth();
pic1Rect.bottom = (int) pic1.getY() + pic1.getHeight();
pic2Rect.left = (int) pic2.getX();
pic2Rect.top = (int) pic2.getY();
pic2Rect.right = (int) pic2.getX() + pic2.getWidth();
pic2Rect.bottom = (int) pic2.getY() + pic2.getHeight();
Log.e("TEST", "handleCollision: " + handleCollision(pic1Rect, pic2Rect));
}
});
}
private boolean handleCollision(Rect one, Rect two) {
boolean hasCollision = hasCollision(one, two);
if (collisionEventHandled != hasCollision) {
collisionEventHandled = hasCollision;
return hasCollision;
}
return false;
}
private static boolean hasCollision(Rect one, Rect two) {
return (one.left < two.right &&
one.right > two.left &&
one.top < two.bottom &&
one.bottom > two.top);
}
}
and the xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:focusableInTouchMode="true">
<ImageView
android:id="#+id/pic1"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerInParent="true"
android:background="#android:color/holo_red_dark"/>
<ImageView
android:id="#+id/pic2"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#android:color/holo_green_light"/>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>

Android, overlapping imageViews

I am creating programatically ImageViews and dragging them in the same layout.
I would like to disable overlapping for this ImageView. Is there a setting to be applied to disable overlap when I create every ImageView programatically or something else ?
public class MainActivity extends ActionBarActivity {
private int offset_x = 0;
private int offset_y = 0;
RelativeLayout canvas;
LinearLayout buttonslayout;
boolean isselected = false;
View selected_item = null;
int test1,test2;
Button save,newdoor,newwindow,rotate;
TextView xcoord,ycoord;
//static final int SNAP_GRID_INTERVAL = 43;
static final int SNAP_GRID_INTERVAL = 44;
static final int SNAP_GRID_INTERVAL2 = 25;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
canvas = (RelativeLayout) findViewById(R.id.container2);
ViewGroup vg = (ViewGroup)findViewById(R.id.container3);
//buttonslayout = (LinearLayout) findViewById(R.id.container3);
save = (Button) findViewById(R.id.savebtn);
newdoor = (Button) findViewById(R.id.btnnewdoor);
newwindow = (Button) findViewById(R.id.btnnewwindow);
xcoord = (TextView) findViewById(R.id.xcoord);
ycoord = (TextView) findViewById(R.id.ycoord);
rotate = (Button) findViewById(R.id.rotate);
newwindow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final int lungime = 66;
final int inaltime = 20;
final int []lastcoords = new int[2];
final int canvasWidth = canvas.getWidth();
final int canvasHeight = canvas.getHeight();
RelativeLayout mylayout = (RelativeLayout) findViewById(R.id.container2);
final View canvas = ((View) v.getParent());
final int []coordwall = new int[2];
mylayout.getLocationInWindow(coordwall);
final ImageView image = new ImageView(getBaseContext());
image.setBackgroundResource(R.drawable.element_window);
mylayout.addView(image);
image.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
offset_x = (int)event.getX();
offset_y = (int)event.getY();
selected_item = v;
isselected = true;
xcoord.setText("X: "+lastcoords[0]);
ycoord.setText("Y: "+lastcoords[1]);
Log.i("test","Isselected = "+isselected);
break;
default:
break;
}
return false;
}
});
rotate.setOnClickListener(new View.OnClickListener() {
int grad=0;
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(grad!=1)
{
image.setRotation(90);
grad=1;
}
else
{
image.setRotation(180);
grad=0;
}
}
});
mylayout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
MarginLayoutParams marginParams = new MarginLayoutParams(v.getLayoutParams());
switch(event.getAction())
{
case MotionEvent.ACTION_UP:
isselected = false;
Log.i("test","Isselected = "+isselected);
break;
case MotionEvent.ACTION_MOVE:
if(isselected == true)
{
View canvas = ((View) v.getParent());
final int width = v.getWidth() / 2, height = v.getHeight() / 2;
int x = (int)event.getX() - offset_x;
int y = (int)event.getY() - offset_y;
int w = getWindowManager().getDefaultDisplay().getWidth() - 100;
int h = getWindowManager().getDefaultDisplay().getHeight() - 100;
int rawX = (int) event.getRawX(), rawY = (int) event.getRawY();
int x_coord = (int) event.getRawX() - coordwall[0] - width;
int y_coord = (int) event.getRawY() - coordwall[1] - height;
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
new ViewGroup.MarginLayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
if (rawY < coordwall[1] + inaltime / 2)
lp.topMargin = 0;
else
if (rawY >= coordwall[1] + canvasHeight - inaltime )
lp.topMargin = canvasHeight - inaltime*2;
else
lp.topMargin = y / SNAP_GRID_INTERVAL * SNAP_GRID_INTERVAL;
if(rawX < coordwall[0] + lungime / 2)
lp.leftMargin = 0;
else
if(rawX >= coordwall[0] + canvasWidth - lungime)
{
lp.leftMargin = canvasWidth - lungime*2;
Log.i("arry","leftmargin = " + lp.leftMargin);
}
else
lp.leftMargin = x / SNAP_GRID_INTERVAL * SNAP_GRID_INTERVAL;
lastcoords[0] = lp.leftMargin;
lastcoords[1] = lp.topMargin;
xcoord.setText("X: "+lp.leftMargin);
ycoord.setText("Y: "+lp.topMargin);
lp.setMargins(lp.leftMargin, lp.topMargin, 0, 0);
selected_item.setLayoutParams(lp);
}
break;
default:
break;
}
return true;
}
});
}
});
And the xml:
LinearLayout 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"
android:background="#000000"
android:orientation="horizontal"
tools:context="com.example.draganddrop.MainActivity"
tools:ignore="MergeRootFrame" >
<LinearLayout
android:id="#+id/container3"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#848484"
android:orientation="vertical" >
<Button
android:id="#+id/savebtn"
style="#drawable/new_wall"
android:layout_width="100dp"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
android:background="#drawable/new_wall"
android:textSize="13sp" />
<Button
android:id="#+id/btnnewwindow"
android:layout_width="100dp"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
android:background="#drawable/new_window"
android:textSize="13sp" />
<Button
android:id="#+id/btnnewdoor"
android:layout_width="100dp"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
android:background="#drawable/new_door"
android:textSize="14sp" />
<TextView
android:id="#+id/xcoord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:text="X: " />
<TextView
android:id="#+id/ycoord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="Y: " />
<Button
android:id="#+id/rotate"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Rotate" />
</LinearLayout>
<RelativeLayout
android:id="#+id/container2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF" >
</RelativeLayout>
</LinearLayout>
It is not very clear what exactly You want to do, but if I am understand You the right way, You want to set some ImageViews to a layout programmatically? Why are Your Views overlapping? I think You have to set the layout Paramaters for Your view container:
//after onCreate in the activity, create the LinearLayout (for example)
//and set the LayoutParams, if You have no one declared in Your xml
LinearLayout linearLayout= new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
//then create the imageView, set the image inside and add it to the container
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.drawable.your_image);
imageView.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
linearLayout.addView(imageView);
//set all as content
setContentView(linearLayout);
Have You done it in this way? If not, try it, also if You want to set multiple imageViews or some other Layout, You have to play a little bit with the LayoutParams.

Creating Multiple ImageButtons in a Single Activity Programatically

I have a single image myimage.png which is placed in my res-drawable folder.
I have to create 50 ImageButtons in an activity all using this same image.
And then when a user clicks i need to pop out a toast saying button number i was clicked.
Here's what I have done:
public class AllImageButtons extends Activity {
int screendimesionx;
int screendimesiony;
ImageButton imageButton;
ImageButton allImageButtons[] = new ImageButton[50];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.allbuttonimages);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
screendimesiony = metrics.heightPixels;
screendimesionx = metrics.widthPixels;
createButtonsAndAddListener();
}
public void createButtonsAndAddListener() {
for (int i = 0; i < 50; i++) {
imageButton = (ImageButton) findViewById(R.id.myimage);
float buttonimagey = imageButton.getDrawable().getBounds().height();
float buttonimagex = imageButton.getDrawable().getBounds().width();
float xspaceforeachbuttonimage = screendimesionx/50;
LayoutParams par = (LayoutParams)imageButton.getLayoutParams();
par.leftMargin = (int) (i*xspaceforeachbuttonimage);
par.topMargin = 0;
imageButton.setLayoutParams(par);
allImageButtons[i] = imageButton;
allImageButtons[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(AllbuttonimagesForSelectionActivity.this,
"ImageButton is clicked!", Toast.LENGTH_SHORT)
.show();
}
});
}
}}
and then there is the associated xml file allbuttonimages.xml:
<?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:orientation="vertical" >
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/myimage" />
</LinearLayout>
This xml layout displays only the last ImageButton from the loop.
My Question:
How can i dynamically create all 50 ImageButtons from the same image in a single view ?
You are not adding the buttons to the parent .
use addView(yourImageButton) to add your image button to activity
The button that is visible now is the one in xml
You should create new imageButton using new
eg: ImageButton imgBtn = new ImageButton(this)
Then set the properties and addView to your parent Layout
You will not get 50 buttons with the one defined in xml
You have one button in layout and you are calling findViewById for that.
You need to create new buttons each time and add it to the linearlayout.
public void createButtonsAndAddListener() {
for (int i = 0; i < 50; i++) {
imageButton = new ImageButton(this);
imageButton.setImageResource(R.drawable.myimage);
float buttonimagey = imageButton.getDrawable().getBounds().height();
float buttonimagex = imageButton.getDrawable().getBounds().width();
float xspaceforeachbuttonimage = screendimesionx/50;
LayoutParams par = (LayoutParams)imageButton.getLayoutParams();
par.leftMargin = (int) (i*xspaceforeachbuttonimage);
par.topMargin = 0;
imageButton.setLayoutParams(par);
allImageButtons[i] = imageButton;
allImageButtons[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(AllbuttonimagesForSelectionActivity.this,
"ImageButton is clicked!", Toast.LENGTH_SHORT)
.show();
}
});
((LinearLayout)findViewById(R.id.ll)).addView(imageButton);
}
Layout:
<?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:orientation="vertical" android:id="#+id/ll">
</LinearLayout>
Your code wont add images to the layout. Get the parent layout in code and add images to it using addView. Between you do not need the image button in the xml. You can do some thing like this:
LinearLayout parent = (LinearLayout)findViewById(R.id.the_parent_layout);
for(int i = 0; i< 50; i++){
ImageButton image = new ImageButton(context);
//set whatever properties you want
//then add to the parent
parent.addView(image); // you can also specify the layout params here
}
Try This....
for (int i = 0; i < 50; i++) {
ImageButton b1 = new ImageButton(myrefmenu);
b1.setId(100 + i);
b1.setImageResource(R.drawable.imagename);
// b1.setText(adapt_objmenu.city_name_array[i]);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
if (i > 0) {
lp.addRule(RelativeLayout.RIGHT_OF, b1.getId() - 1);
}
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(AllbuttonimagesForSelectionActivity.this,
"ImageButton is clicked!", Toast.LENGTH_SHORT)
.show();
}
});
b1.setLayoutParams(lp);
relative.addView(b1);
}

android, add multiple ImageViews onTouch event

I've just started programming for Android. I've searched for my problem a lot, but the advises didn't help me. I want the same images appear on screen in the touch coordinates. That's what I've done:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View main_view = (View)findViewById(R.id.main_view);
main_view.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
ImageView image = new ImageView(getApplicationContext());
//ImageView image = (ImageView)findViewById(R.id.broken);
image.setImageResource(R.drawable.broken);
image.setX(event.getX() + image.getWidth() / 2);
image.setY(event.getY() - image.getHeight() / 2);
LinearLayout top_layout = (LinearLayout) findViewById(R.id.top_layout);
LayoutParams p = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
image.setLayoutParams(p);
top_layout.addView(image);
return true;
}
});
}
Everything seems right to me, but when touching the screen, nothing happens. Where is the obvious mistake I've made? Thanks in advance.
You can't do that in a LinearLayout.
Let's use a FrameLayout instead.
activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/framelayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
MainActivity.java
public class MainActivity extends Activity {
private FrameLayout mLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLayout = (FrameLayout) findViewById(R.id.framelayout);
mLayout.setOnTouchListener(mListener);
}
private OnTouchListener mListener = new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
return true;
case MotionEvent.ACTION_UP:
// decode the resource to get width and height
Options opts = new Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher, opts);
int imageWidth = opts.outWidth;
int imageHeight = opts.outHeight;
// set the imageview's top and left margins
FrameLayout.LayoutParams lp = new LayoutParams(imageWidth, imageHeight);
lp.leftMargin = (int) (event.getX() - (imageWidth / 2));
lp.topMargin = (int) (event.getY() - (imageHeight / 2));
ImageView image = new ImageView(MainActivity.this);
image.setImageResource(R.drawable.ic_launcher);
mLayout.addView(image, lp);
return false;
}
return false;
}
};
}
setX and setY don't set the images position. It basically scrolls the image in place. The position is controlled by its parent view. Since its parent is a linear layout, it will always be placed below or to the right of the thing above it in the layout. If you want to place it somewhere exactly, you need to put it in a parent that supports that, such as the deprecated AbsoluteLayout.

Categories

Resources