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

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>

Related

How can I animate specific views?

I want to animate Bloc A to slide up and Bloc B to slide down when I move from Activity 1 to Activity 2
Can someone bring me a solution for this ? Thanks a lot for your help
Here's an illustration of what I want :
Try the following:
1) MainActivity.class:-------------
public class MainActivity extends AppCompatActivity implements Listener {
private Drawer m_Drawer;
private Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m_Drawer = new Drawer(this, this);
b = (Button) findViewById(R.id.b); // click on this button to open drawer.
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
m_Drawer.openDrawer();
}
});
}
#Override
public void AnimationFinished(int state) {
if (state == 1) {
b.setVisibility(View.VISIBLE); // you can start a new activity or do whatever here.
}else if(state == 0){
b.setVisibility(View.GONE);
}
}
}
2) Drawer.class:-------
public class Drawer {
private static final String TAG = "Drawer";
private RelativeLayout topDrawer;//2
private RelativeLayout bottomDrawer;//2
private Activity activity;
private static final int DRAWER_UP = 1;
private static final int DRAWER_DOWN = 0;
private int mainlayoutHeight;
private TextView drawerTxt1;
private TextView drawerTxt;
private int direct;
private ConstraintLayout mainLayout;//1
private float mDownMotionX = 0;
private float mDownMotionY = 0;
private final int SWIPE_SENSITIVITY = 10;
private final int SWIPE_X_SENSITIVITY = 20;
private final int SWIPE_Y_SENSITIVITY_MIN = 0;
private int SWIPE_Y_SENSITIVITY_MAX = 0;
private Listener callback;
Drawer(Activity mainActivity , Listener l) {
activity = mainActivity;
if(l != null){
this.callback = l;
}
initialize();
getLayoutHeight();
}
private void initialize() {
topDrawer = (RelativeLayout) activity.findViewById(R.id.top_drawer);//2
drawerTxt1 = (TextView) topDrawer.findViewById(R.id.drawer_txt1);
drawerTxt1.setText("BLOCK A");
bottomDrawer = (RelativeLayout) activity.findViewById(R.id.bottom_drawer);//2
drawerTxt = (TextView) bottomDrawer.findViewById(R.id.drawer_txt);
drawerTxt.setText("BLOCK B");
topDrawer.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent ev) {
Log.e(TAG, "Touch View");
final int action = ev.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
// Remember where the motion event started
mDownMotionX = ev.getX();
mDownMotionY = ev.getY();
break;
case MotionEvent.ACTION_MOVE:
// Scroll to follow the motion event
final float x = ev.getX();
final float y = ev.getY();
SWIPE_Y_SENSITIVITY_MAX = getScreenHeight();
if (Math.abs(y - mDownMotionY) >= SWIPE_SENSITIVITY &&
(mDownMotionY > SWIPE_Y_SENSITIVITY_MIN &&
mDownMotionY <= SWIPE_Y_SENSITIVITY_MAX) &&
Math.abs(x - mDownMotionX) <= SWIPE_X_SENSITIVITY) {
if ((y - mDownMotionY) > 0) {
Log.d(TAG, "Dragging Down");
}
} else if ((y - mDownMotionY) < 0) {
closeDrawer();
Log.d(TAG, "Dragging Up");
}
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_CANCEL:
break;
}
return true;
}
});
bottomDrawer.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent ev) {
Log.e(TAG, "Touch View");
final int action = ev.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
// Remember where the motion event started
mDownMotionX = ev.getX();
mDownMotionY = ev.getY();
break;
case MotionEvent.ACTION_MOVE:
// Scroll to follow the motion event
final float x = ev.getX();
final float y = ev.getY();
SWIPE_Y_SENSITIVITY_MAX = getScreenHeight();
if (Math.abs(y - mDownMotionY) >= SWIPE_SENSITIVITY &&
(mDownMotionY > SWIPE_Y_SENSITIVITY_MIN &&
mDownMotionY <= SWIPE_Y_SENSITIVITY_MAX) &&
Math.abs(x - mDownMotionX) <= SWIPE_X_SENSITIVITY) {
if ((y - mDownMotionY) > 0) {
Log.d(TAG, "Dragging Down");
closeDrawer();
}
} else if ((y - mDownMotionY) < 0) {
Log.d(TAG, "Dragging Up");
}
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_CANCEL:
break;
}
return true;
}
});
}
//********************************************************************************************** Open and Close the Drawer /Animation/
private void drawerMovement(int movement){
switch (movement) {
case DRAWER_UP: // --------------------------------------------------------------------- Drawer UP
topDrawer.animate().translationY(-mainlayoutHeight/2); // you can add two animation listeners, but for now one is enough.
bottomDrawer.animate().translationY(mainlayoutHeight)
.setListener(new animationListener());
direct = DRAWER_UP;
break;
case DRAWER_DOWN: // ------------------------------------------------------------------- Drawer DOWN
topDrawer.animate().translationY(0);
bottomDrawer.animate().translationY(mainlayoutHeight/2)
.setListener(new animationListener());
direct = DRAWER_DOWN;
break;
}
}
//********************************************************************************************** Animation Listener
private class animationListener implements Animator.AnimatorListener {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
callback.AnimationFinished(direct);
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {}
}
private void closeDrawer(){
drawerMovement(DRAWER_UP);
}
public void openDrawer(){
drawerMovement(DRAWER_DOWN);
}
// ********************************************************************************************* Get the Layout Height
private void getLayoutHeight() {
mainLayout = (ConstraintLayout) activity.findViewById(R.id.main_layout);//1
ViewTreeObserver vto = mainLayout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
mainlayoutHeight = mainLayout.getMeasuredHeight();
topDrawer.setY(0);
bottomDrawer.setY(mainlayoutHeight/2);
ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_PARENT, mainlayoutHeight/2);//1
topDrawer.setLayoutParams(params);
bottomDrawer.setLayoutParams(params);
Log.d("Test", "Layout Height: " + mainlayoutHeight );
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
mainLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
mainLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
}
});
}
private int getScreenHeight(){
DisplayMetrics displayMetrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
return displayMetrics.heightPixels;
}
}
3) Listener interface:----------
public interface Listener {
public void AnimationFinished(int state);
}
4) main_activity.xml:----------
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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"
android:id="#+id/main_layout"
tools:context=".MainActivity">
<RelativeLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="#+id/bottom_drawer"
android:background="?attr/colorPrimary">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_txt"
android:textSize="28sp"
android:gravity="center_horizontal|center_vertical" />
</RelativeLayout>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="#+id/top_drawer"
android:background="?attr/colorAccent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_txt1"
android:textSize="28sp"
android:gravity="center_horizontal|center_vertical" />
</RelativeLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="100dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:gravity="center_horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/b"
android:text="Open Drawer"
android:textAllCaps="false"
android:layout_gravity="center"
android:visibility="gone"
android:textSize="28sp"
android:textColor="#android:color/white">
</Button>
</LinearLayout>
</android.support.constraint.ConstraintLayout>

AppCompat-styled Rangebar (Seekbar with two Thumbs)

I found a couple of questions regarding rangebars (seekbars with two thumbs) on Android, like Android Seekbar with two thumbs or working with SeekBar with two thumbs. All the answers point to components that look quite outdated since Material Design and thus AppCompat was released.
What I'm looking for is a Rangebar that looks like the AppCompatSeekBar with two thumbs. Are there any available libraries or ways to hack into the platform SeekBar so that the available resources can be reused?
This is my first time answering something here.
I created my own custom rangebar as follows.
Create the following files.
RangeBar.java
public class RangeBar extends FrameLayout{
int minVal = 0;
int maxVal = 100;
Context context;
ImageView leftThumb;
ImageView rightThumb;
View view;
int leftThumbPos = 0;
int rightThumbPos = 100;
public RangeBar(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
this.view = inflate(getContext(), R.layout.range_seekbar, null);
addView(this.view);
}
public RangeBar(Context context){
super(context);
this.context = context;
this.view = inflate(getContext(), R.layout.range_seekbar, null);
addView(this.view);
}
public void create() {
leftThumb = (ImageView)findViewById(R.id.left_thumb);
rightThumb = (ImageView)findViewById(R.id.right_thumb);
final View leftBar = findViewById(R.id.left_bar);
final View rightBar = findViewById(R.id.right_bar);
final View middleBar = findViewById(R.id.middle_bar);
final LinearLayout.LayoutParams leftBarLayoutParams = (LinearLayout.LayoutParams) leftBar.getLayoutParams();
final LinearLayout.LayoutParams rightBarLayoutParams = (LinearLayout.LayoutParams) rightBar.getLayoutParams();
final LinearLayout.LayoutParams middleBarLayoutParams = (LinearLayout.LayoutParams) middleBar.getLayoutParams();
final LinearLayout llRangeSeekbar = (LinearLayout)findViewById(R.id.ll_range_seekbar);
((TextView)findViewById(R.id.tv_range_max)).setText(maxVal+"");
((TextView)findViewById(R.id.tv_range_min)).setText(minVal+"");
leftThumbPos = Integer.parseInt(((TextView)findViewById(R.id.tv_range_min)).getText()+"");
rightThumbPos = Integer.parseInt(((TextView)findViewById(R.id.tv_range_max)).getText()+"");
leftThumb.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int diff = maxVal - minVal;
if(diff < 0){
diff = 100;
minVal = 0;
maxVal = 100;
}
float width = llRangeSeekbar.getWidth();
float gap = leftThumb.getWidth();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
leftThumb.bringToFront();
return true;
}else if (event.getAction() == MotionEvent.ACTION_MOVE ) {
float temp1 = leftBarLayoutParams.weight;
float temp2 = middleBarLayoutParams.weight;
leftBarLayoutParams.weight += event.getX()/width;
middleBarLayoutParams.weight = 1 - (leftBarLayoutParams.weight + rightBarLayoutParams.weight);
int tempMaxVal = Integer.parseInt(((TextView)findViewById(R.id.tv_range_max)).getText()+"");
int tempMinVal = (int)(diff*leftBarLayoutParams.weight + minVal);
if(tempMinVal > tempMaxVal){
tempMinVal = tempMaxVal;
}
if(tempMinVal < minVal){
tempMinVal = minVal;
}
((TextView)findViewById(R.id.tv_range_min)).setText(tempMinVal + "");
if(middleBarLayoutParams.weight > gap/width && leftBarLayoutParams.weight >= 0){
leftBar.setLayoutParams(leftBarLayoutParams);
middleBar.setLayoutParams(middleBarLayoutParams);
}else {
if(leftBarLayoutParams.weight < 0){
leftBarLayoutParams.weight = 0;
middleBarLayoutParams.weight = 1 - (rightBarLayoutParams.weight + leftBarLayoutParams.weight);
}else{
middleBarLayoutParams.weight = gap/width + (tempMaxVal - tempMinVal)/(1.0f*diff);
leftBarLayoutParams.weight = 1 - (middleBarLayoutParams.weight + rightBarLayoutParams.weight);
}
leftBar.setLayoutParams(leftBarLayoutParams);
middleBar.setLayoutParams(middleBarLayoutParams);
}
return true;
}else if (event.getAction() == MotionEvent.ACTION_UP) {
leftThumbPos = Integer.parseInt(((TextView)findViewById(R.id.tv_range_min)).getText()+"");
return true;
}else
{
return false;
}
}
});
rightThumb.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int diff = maxVal - minVal;
if(diff < 0){
diff = 100;
minVal = 0;
maxVal = 100;
}
float width = llRangeSeekbar.getWidth();
float gap = leftThumb.getWidth();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
rightThumb.bringToFront();
return true;
}else if (event.getAction() == MotionEvent.ACTION_MOVE) {
float temp1 = middleBarLayoutParams.weight;
float temp2 = rightBarLayoutParams.weight;
rightBarLayoutParams.weight -= (event.getX()/width);
middleBarLayoutParams.weight = 1 - (rightBarLayoutParams.weight + leftBarLayoutParams.weight);
int tempMinVal = Integer.parseInt(((TextView)findViewById(R.id.tv_range_min)).getText()+"");
int tempMaxVal = (int)(diff*(1 - rightBarLayoutParams.weight) + minVal);
if(tempMaxVal < tempMinVal){
tempMaxVal = tempMinVal;
}
if(tempMaxVal > maxVal){
tempMaxVal = maxVal;
}
((TextView)findViewById(R.id.tv_range_max)).setText(tempMaxVal+"");
if(middleBarLayoutParams.weight > gap/width && rightBarLayoutParams.weight >= 0){
rightBar.setLayoutParams(rightBarLayoutParams);
middleBar.setLayoutParams(middleBarLayoutParams);
}else{
if(rightBarLayoutParams.weight < 0){
rightBarLayoutParams.weight = 0;
middleBarLayoutParams.weight = 1 - (rightBarLayoutParams.weight + leftBarLayoutParams.weight);
}else {
middleBarLayoutParams.weight = gap/width + (tempMaxVal - tempMinVal)/(1.0f*diff);
rightBarLayoutParams.weight = 1 - (leftBarLayoutParams.weight + middleBarLayoutParams.weight);
}
rightBar.setLayoutParams(rightBarLayoutParams);
middleBar.setLayoutParams(middleBarLayoutParams);
}
return true;
}else if (event.getAction() == MotionEvent.ACTION_UP) {
rightThumbPos = Integer.parseInt(((TextView)findViewById(R.id.tv_range_max)).getText()+"");
return true;
}
else
{
return false;
}
}
});
}
public int getMinVal() {
return minVal;
}
public void setMinVal(int minVal) {
this.minVal = minVal;
}
public int getMaxVal() {
return maxVal;
}
public void setMaxVal(int maxVal) {
this.maxVal = maxVal;
}
public int getLeftThumbPos() {
return leftThumbPos;
}
public void setLeftThumbPos(int leftThumbPos) {
this.leftThumbPos = leftThumbPos;
}
public int getRightThumbPos() {
return rightThumbPos;
}
public void setRightThumbPos(int rightThumbPos) {
this.rightThumbPos = rightThumbPos;
}
}
and range_seekbar.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:gravity="center"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="horizontal"
android:gravity="center"
android:id="#+id/ll_range_seekbar"
android:layout_height="wrap_content">
<View
android:layout_width="0dp"
android:layout_weight="0"
android:id="#+id/left_bar"
android:background="#color/light_grey"
android:layout_height="1dp"/>
<RelativeLayout
android:layout_width="0dp"
android:layout_weight="1"
android:id="#+id/middle_bar"
android:layout_height="wrap_content">
<View
android:layout_width="match_parent"
android:layout_centerVertical="true"
android:id="#+id/middle_view"
android:layout_toRightOf="#+id/left_thumb"
android:layout_toLeftOf="#+id/right_thumb"
android:background="#color/color_select_sky_blue"
android:layout_height="1dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/left_thumb"
android:layout_alignParentLeft="true"
android:src="#drawable/seek_thumb_normal"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/right_thumb"
android:layout_alignParentRight="true"
android:src="#drawable/seek_thumb_normal"/>
</RelativeLayout>
<View
android:layout_width="0dp"
android:layout_weight="0"
android:id="#+id/right_bar"
android:background="#color/light_grey"
android:layout_height="1dp"/>
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:id="#+id/tv_range_min"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:id="#+id/tv_range_max"/>
</RelativeLayout>
</LinearLayout>
Use them in the activity as follows.
Test.java
public class Test extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
RangeBar rangeBar = (RangeBar) findViewById(R.id.rangebar);
rangeBar.setMinVal(25);
rangeBar.setMaxVal(50);
rangeBar.create();
}
}.
This is the layout file for the activity.
test.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:gravity="center"
android:layout_margin="50dp"
android:layout_height="match_parent">
<com.example.pankajkumar.Utils.RangeBar
android:id="#+id/rangebar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

Draw lines following your finger between two Views(ImageViews)

I have used(seen) a lot of examples across the SO and what I need exactly is to draw a line between two images view on a layout as:
All the examples or samples I have seen, Just extends the class with view and it is That Class is set as ContentView As,
public class DrawView extends View {
Paint paint = new Paint();
public DrawView(Context context) {
super(context);
paint.setColor(Color.BLACK);
}
#Override
public void onDraw(Canvas canvas) {
canvas.drawLine(0, 50, 350, 50, paint);
}
}
And,...
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
DrawView drawView = new DrawView(this);
setContentView(drawView);
}
Actually , it is a nice way but How can I add these Images to the Canvas (or) How to load my Layout (XML file) to draw lines between them.
Any kind of little push also helps me a lot in this work. Thanks.
I had implemented such kind of application.
I'm posting my code, might be this can help you.
MainActivity.java class:
public class MainActivity extends Activity {
public TableLayout t1;
public TableRow tr1;
public TableRow tr2;
public TableRow tr3;
public ImageButton i11;
public ImageButton i21;
public ImageButton i12;
public ImageButton i22;
public ImageButton i31;
public ImageButton i32;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t1 = (TableLayout) findViewById(R.id.tableLayout1);
tr1 = (TableRow) findViewById(R.id.tableRow1);
tr2 = (TableRow) findViewById(R.id.tableRow2);
tr3 = (TableRow) findViewById(R.id.tableRow3);
i11 = (ImageButton) findViewById(R.id.ibACol1);
i12 = (ImageButton) findViewById(R.id.ibCCol3);
i21 = (ImageButton) findViewById(R.id.ibBCol1);
i22 = (ImageButton) findViewById(R.id.ibACol3);
i31 = (ImageButton) findViewById(R.id.ibCCol1);
i32 = (ImageButton) findViewById(R.id.ibBCol3);
RelativeLayout rl = (RelativeLayout) findViewById(R.id.RelativeLayout1);
DrawPanel drawingPanel = new DrawPanel(getApplicationContext());
rl.addView(drawingPanel);
}
public class DrawPanel extends View {
private Paint paint;
private Paint paint1;
private Paint paint2;
// Canvas c;
MainActivity m1 = new MainActivity();
int count = 0;
int ans = 0, ansPrev;
int temp1, temp2;
int color = 0;
String str = "";
public boolean tmp;
#SuppressWarnings("rawtypes")
private ArrayList points;
#SuppressWarnings("rawtypes")
private ArrayList strokes;
#SuppressWarnings("rawtypes")
public DrawPanel(Context context) {
super(context);
points = new ArrayList();
// points1 = new ArrayList();
// points2 = new ArrayList();
strokes = new ArrayList();
paint = createPaint(Color.BLUE, 11);
paint1 = createPaint(Color.GREEN, 11);
paint2 = createPaint(Color.RED, 11);
}
#SuppressWarnings("rawtypes")
public void onDraw(Canvas c) {
super.onDraw(c);
// this.setBackgroundColor(Color.WHITE);
for (Object obj : strokes) {
drawStroke((ArrayList) obj, c, color);
}
drawStroke(points, c, color);
color = 0;
}
#SuppressWarnings({ "unchecked", "rawtypes" })
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getActionMasked() == MotionEvent.ACTION_MOVE) {
points.add(new Point((int) event.getX(), (int) event.getY()));
color = getColor();
invalidate();
}
if (event.getActionMasked() == MotionEvent.ACTION_UP) {
try {
ansPrev = ans;
for (int r = 0; r < t1.getChildCount(); r++) {
int y = (int) t1.getChildAt(r).getY();
if ((int) event.getY() >= y
&& (int) event.getY() < (y + t1.getChildAt(r)
.getHeight())) {
// View v = t1.getChildAt(r);
for (int i = 0; i < ((TableRow) t1.getChildAt(r))
.getChildCount(); i += 2) {
int x1 = (int) tr1.getChildAt(i).getX();
if ((int) event.getX() >= x1
&& (int) event.getX() < (x1 + tr1
.getChildAt(i).getWidth())) {
// Toast.makeText(getApplicationContext(),
// "Row "+(r+1)+", Column "+(i+1)+"Selected.",
// Toast.LENGTH_SHORT).show();
if (count == 1) {
// str =
// (String)((ImageButton)((TableRow)t1.getChildAt(r)).getChildAt(i)).getContentDescription();
int len1 = (int) ((ImageButton) ((TableRow) t1
.getChildAt(temp1))
.getChildAt(temp2))
.getContentDescription()
.length();
int len2 = (int) ((ImageButton) ((TableRow) t1
.getChildAt(r)).getChildAt(i))
.getContentDescription()
.length();
String str1 = (String) ((ImageButton) ((TableRow) t1
.getChildAt(r)).getChildAt(i))
.getContentDescription()
.subSequence(0, 1);
if (str1.equals(str) && len1 != len2) {
ans = ans + 1;
tmp = true;
color = 1;
// drawStroke(points, c, color);
((ImageButton) ((TableRow) t1
.getChildAt(temp1))
.getChildAt(temp2))
.setSelected(false);
Toast.makeText(
getApplicationContext(),
"Answer Matched. \n Your score is: "
+ ans,
Toast.LENGTH_SHORT).show();
count = 0;
} else {
ans = ans - 1;
tmp = false;
color = 2;
// drawStroke(points, c, color);
((ImageButton) ((TableRow) t1
.getChildAt(temp1))
.getChildAt(temp2))
.setSelected(false);
Toast.makeText(
getApplicationContext(),
"Answer not Matched. \n Your score is: "
+ ans,
Toast.LENGTH_SHORT).show();
count = 0;
}
// Toast.makeText(getApplicationContext(),
// "Image "+(i+r+1)+" : "+str+((ImageButton)((TableRow)t1.getChildAt(r)).getChildAt(i)).isSelected(),
// Toast.LENGTH_SHORT).show();
// count=0;
}
}
}
}
// Toast.makeText(getApplicationContext(),
// "Color: "+color, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
// points2.clear();
// points = new ArrayList();
// invalidate();
this.strokes.add(points);
points = new ArrayList();
invalidate();
}
return true;
}
public int getColor() {
return color;
}
private void drawStroke(#SuppressWarnings("rawtypes") ArrayList stroke,
Canvas c, int i1) {
if (stroke.size() > 0 && i1 == 0) {
Point p0 = (Point) stroke.get(0);
for (int i = 1; i < stroke.size(); i++) {
Point p1 = (Point) stroke.get(i);
c.drawLine(p0.x, p0.y, p1.x, p1.y, paint);
p0 = p1;
}
} else if (stroke.size() > 0 && i1 == 1) {
Point p0 = (Point) stroke.get(0);
for (int i = 1; i < stroke.size(); i++) {
Point p1 = (Point) stroke.get(i);
c.drawLine(p0.x, p0.y, p1.x, p1.y, paint1);
p0 = p1;
}
} else if (stroke.size() > 0 && i1 == 2) {
Point p0 = (Point) stroke.get(0);
for (int i = 1; i < stroke.size(); i++) {
Point p1 = (Point) stroke.get(i);
c.drawLine(p0.x, p0.y, p1.x, p1.y, paint2);
p0 = p1;
}
}
}
private Paint createPaint(int color, float width) {
Paint temp = new Paint();
temp.setStyle(Paint.Style.STROKE);
temp.setAntiAlias(true);
temp.setColor(color);
temp.setStrokeWidth(width);
temp.setStrokeCap(Cap.ROUND);
return temp;
}
}
}
main.xml Layout File:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="20dp" >
<ImageButton
android:id="#+id/ibACol1"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#drawable/edu1"
android:contentDescription="#string/A" />
<TextView
android:id="#+id/textView1"
android:layout_width="100dp"
android:layout_height="100dp"
android:text="" />
<ImageButton
android:id="#+id/ibCCol3"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#drawable/edu3"
android:contentDescription="#string/Cat" />
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="20dp" >
<ImageButton
android:id="#+id/ibBCol1"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#drawable/edu2"
android:contentDescription="#string/B" />
<TextView
android:id="#+id/textView2"
android:layout_width="100dp"
android:layout_height="100dp"
android:text="" />
<ImageButton
android:id="#+id/ibACol3"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#drawable/edu1"
android:contentDescription="#string/Apple" />
</TableRow>
<TableRow
android:id="#+id/tableRow3"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="20dp" >
<ImageButton
android:id="#+id/ibCCol1"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#drawable/edu3"
android:contentDescription="#string/C" />
<TextView
android:id="#+id/textView3"
android:layout_width="100dp"
android:layout_height="100dp"
android:text="" />
<ImageButton
android:id="#+id/ibBCol3"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#drawable/edu2"
android:contentDescription="#string/Bee" />
</TableRow>
</TableLayout>
You need to add images to for drawable folder, and this will work for api-level 11 and onwards.

when move the image from bottom to up with animation,not getting the full image

when move the image from bottom to up with animation,not getting the full image,i am declaring imageview width wrap content.when i was moving the down its working perfectly,but when i image dragging up,the showing part comes with animation not getting the full image.
public class MainActivity extends Activity {
// mainLayout is the child of the HorizontalScrollView ...
private LinearLayout mainLayout;
// this is an array that holds the IDs of the drawables ...
private int[] images = { R.drawable.gg, R.drawable.gg, R.drawable.gg,
R.drawable.gg, R.drawable.gg, R.drawable.gg };
int status = 0;
int Measuredwidth = 0, MeasuredHeight = 0;
float x = 0;
boolean first = true;
ImageButton btn;
View cell = null;
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();
PointF startPoint = new PointF();
static final int NONE = 0;
static final int DRAG = 1;
Bitmap icon;
int mode = NONE;
AnimationListener animx;
/** Called when the activity is first created. */
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
mainLayout = (LinearLayout) findViewById(R.id.linearLayout);
for (int i = 0; i < images.length; i++) {
cell = getLayoutInflater().inflate(R.layout.image, null);
final ImageView img = (ImageView) cell.findViewById(R.id.imageView);
img.setImageResource(images[i]);
// mainLayout.addView(cell);
// }
final LinearLayout ll = (LinearLayout) cell
.findViewById(R.id.lllayout);
Point size = new Point();
WindowManager w = getWindowManager();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
w.getDefaultDisplay().getSize(size);
MeasuredHeight = size.y;
Measuredwidth = size.x;
} else {
Display d = w.getDefaultDisplay();
Measuredwidth = d.getWidth();
MeasuredHeight = d.getHeight();
}
// final AbsoluteLayout aalayout = (AbsoluteLayout) cell
// .findViewById(R.id.absLayout);
btn = (ImageButton) cell.findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "button 1 pressed",
2000).show();
}
});
img.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(final View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
status = 0;
System.out.println("sdhsjdkklkl");
} else if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (first) {
x = event.getX();
first = false;
System.out.println("matrix: " + matrix);
savedMatrix.set(matrix);
mode = DRAG;
startPoint.set(img.getLeft(), event.getY());
} else {
startPoint.set(img.getLeft(), event.getY());
}
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
float dx = event.getX() - startPoint.x;
final float dy = event.getY() - startPoint.y;
float setheight = btn.getBottom() + 6;
if (dy > 0) {
System.out.println("saved matrix:" + savedMatrix);
matrix.set(savedMatrix);
System.out.println("y value: " + dy);
matrix.postTranslate(img.getLeft(), 80);
ll.setVisibility(View.VISIBLE);
img.setImageMatrix(matrix);
}
else if (dy < 0) {
int fromLoc[] = new int[2];
img.getLocationOnScreen(fromLoc);
final float startX = fromLoc[0];
final float startY = fromLoc[1];
int toLoc[] = new int[2];
img.getLocationOnScreen(toLoc);
final float destX = 0;
final float destY = img.getTop();
ll.setVisibility(View.GONE);
TranslateAnimation mAnimation = new TranslateAnimation(
0, 0, 0, -80);
mAnimation.setDuration(10000);
mAnimation.setRepeatCount(0);
mAnimation
.setInterpolator(new LinearInterpolator());
mAnimation.setFillAfter(true);
img.setAnimation(mAnimation);
}
}
return true;
}
});
System.out.println("bmgbgklb");
mainLayout.addView(cell);
}
}
}
my main xml is:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<HorizontalScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="1dip" >
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>
</HorizontalScrollView>
</RelativeLayout>
my sub xml is:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginRight="2dip"
android:scaleType="matrix"
android:src="#drawable/dd" >
</ImageView>
<LinearLayout
android:id="#+id/lllayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:visibility="invisible" >
<ImageButton
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="20dip"
android:background="#drawable/orangearrow_over"
android:focusable="true" />
<ImageButton
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:background="#drawable/orangearrow_over" />
<ImageButton
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dip"
android:background="#drawable/orangearrow_over" />
</LinearLayout>
</FrameLayout>

Adding multiple image views programmatically

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.

Categories

Resources