AlertDialog dispatchTouchEvent - java

I want to transfer motionevent to dialog from view onTouchListener
I tried AlertDialog.dispatchTouchEvent but this doesnt work, event just stops at my view and dont go any further.
Code:
final View v = new View(this);
v.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
final WindowManager.LayoutParams params = new WindowManager.LayoutParams();
params.format = PixelFormat.TRANSLUCENT;
params.width = WindowManager.LayoutParams.MATCH_PARENT;
params.height = WindowManager.LayoutParams.MATCH_PARENT;
params.packageName = getPackageName();
getWindowManager().addView(v,params);
v.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v,MotionEvent event) {
if(event.getAction()==MotionEvent.ACTION_UP) {
d.getButton(DialogInterface.BUTTON_NEGATIVE).setText(no);
d.getButton(DialogInterface.BUTTON_POSITIVE).setText(yes);
} else {
int[] pos = new int[2];
Button b = d.getButton(DialogInterface.BUTTON_NEGATIVE);
int w = b.getWidth();
int h = b.getHeight();
b.getLocationOnScreen(pos);
if(event.getRawX() < pos[0] + w && event.getRawX() > pos[0] && event.getRawY() < pos[1] + h && event.getRawY() > pos[1]) {
b.setText(yes);
d.getButton(DialogInterface.BUTTON_POSITIVE).setText(no);
} else {
b.setText(no);
d.getButton(DialogInterface.BUTTON_POSITIVE).setText(yes);
}
}
return d.dispatchTouchEvent(event);
//return false;
}
});
d - dialog that i want to transfer MotionEvent...
yes,no - Strings with text

Related

How do I implement drag and drop in my game?

I have been looking all over SOF and online tutorials, but for some reason I still can't get it to work. I want to implement a drag and drop functionality in my game. Here is the activity:
I want to be able to drag and drop the 4 shapes in the bottom. If the correct shape fits, I want the shape with the "?" to change into the correct shape. Can someone show me how I can do this?
Here is my code:
public class SecondActivity extends AppCompatActivity {
int n;
ImageView shape1, shape2, shape3, shape4, guessShape;
ImageButton exit;
private android.widget.RelativeLayout.LayoutParams layoutParams;
Random rand = new Random();
ImageView[] shapes = new ImageView[4];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
//declare each imageview
shape1 = (ImageView) findViewById(R.id.shape1);
shape2 = (ImageView) findViewById(R.id.shape2);
shape3 = (ImageView) findViewById(R.id.shape3);
shape4 = (ImageView) findViewById(R.id.shape4);
guessShape = (ImageView) findViewById(R.id.guessShape);
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
System.exit(0);
}
});
//add each imageView to the shapes[] array
shapes[0] = shape1;
shapes[1] = shape2;
shapes[2] = shape3;
shapes[3] = shape4;
//store all the shapes in an array
int[] images = new int[]{R.drawable.img_0, R.drawable.img_1, R.drawable.img_2, R.drawable.img_3, R.drawable.img_4,
R.drawable.img_5, R.drawable.img_6, R.drawable.img_7, R.drawable.img_8, R.drawable.img_9, R.drawable.img_10,
R.drawable.img_11, R.drawable.img_12, R.drawable.img_13, R.drawable.img_14, R.drawable.img_15, R.drawable.img_16,
R.drawable.img_17};
//store all the guessShapes in an array
int[] outlines = new int[]{R.drawable.outline_0, R.drawable.outline_1, R.drawable.outline_2,
R.drawable.outline_3, R.drawable.outline_4, R.drawable.outline_5, R.drawable.outline_6,
R.drawable.outline_7, R.drawable.outline_8, R.drawable.outline_9, R.drawable.outline_10,
R.drawable.outline_11, R.drawable.outline_12, R.drawable.outline_13, R.drawable.outline_14,
R.drawable.outline_15, R.drawable.outline_16, R.drawable.outline_17};
//generate 4 random images from the array's and ensure that they don't match each other
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 18; i++) {
list.add(new Integer(i));
}
Collections.shuffle(list);
int whichImg = (int) Math.round((Math.random() * 4));
int img1 = list.get(0);
int img2 = list.get(1);
int img3 = list.get(2);
int img4 = list.get(3);
if (whichImg == 1) {
whichImg = img1;
} else if (whichImg == 2) {
whichImg = img2;
} else if (whichImg == 3) {
whichImg = img3;
} else {
whichImg = img4;
}
int outlineID = outlines[whichImg];
//set the shape in each imageview
guessShape.setBackgroundResource(outlineID);
shape1.setBackgroundResource(images[img1]);
shape2.setBackgroundResource(images[img2]);
shape3.setBackgroundResource(images[img3]);
shape4.setBackgroundResource(images[img4]);
//ensures that 1/4 shape has the guess shape correspondence
final Object currentBackground = guessShape.getBackground().getConstantState();
//for loop to have the guess shape and 1/4 shapes to match
for (int i = 0; i < 18; i++) {
if (currentBackground.equals(getResourceID("outline_" + i, "drawable", getApplicationContext()))) {
int random = new Random().nextInt(shapes.length);
shapes[random].setBackgroundResource(getResourceID("img_" + i, "drawable", getApplicationContext()));
}
//set tags for each view
guessShape.setTag("gShape");
shape1.setTag("S_1");
shape2.setTag("S_2");
shape3.setTag("S_3");
shape4.setTag("S_4");
}
}
//method to get the ID of an image in drawable folder
protected final static int getResourceID(final String resName, final String resType, final Context ctx)
{
final int ResourceID =
ctx.getResources().getIdentifier(resName, resType,
ctx.getApplicationInfo().packageName);
if (ResourceID == 0)
{
throw new IllegalArgumentException
(
"No resource string found with name " + resName
);
}
else
{
return ResourceID;
}
}
}
Although you were not clear enough.
Try this, First make a class that implements onTouchListener
private final class MyTouchListener implements OnTouchListener {
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
ClipData data = ClipData.newPlainText("", "");
DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(
view);
view.startDrag(data, shadowBuilder, view, 0);
view.setVisibility(View.INVISIBLE);
return true;
} else {
return false;
}
}
}
Then define a drag listener
class MyDragListener implements OnDragListener {
Drawable enterShape = getResources().getDrawable(
R.drawable.shape_droptarget);
Drawable normalShape = getResources().getDrawable(R.drawable.shape);
#Override
public boolean onDrag(View v, DragEvent event) {
int action = event.getAction();
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
// do nothing
break;
case DragEvent.ACTION_DRAG_ENTERED:
v.setBackgroundDrawable(enterShape);
break;
case DragEvent.ACTION_DRAG_EXITED:
v.setBackgroundDrawable(normalShape);
break;
case DragEvent.ACTION_DROP:
// Dropped, reassign View to ViewGroup
View view = (View) event.getLocalState();
ViewGroup owner = (ViewGroup) view.getParent();
owner.removeView(view);
LinearLayout container = (LinearLayout) v;
container.addView(view);
view.setVisibility(View.VISIBLE);
break;
case DragEvent.ACTION_DRAG_ENDED:
v.setBackgroundDrawable(normalShape);
default:
break;
}
return true;
}
}
Now simply use these lines
findViewById(R.id.myimage1).setOnTouchListener(new MyTouchListener());
and
findViewById(R.id.bottomleft).setOnDragListener(new MyDragListener());
Here are some tutorials that might help you
Tutorialpoint
Link 2

How to have static dialog fragment method to use throughout app in Android?

I have created a DialogFragment class that I need to show from within a onDragListener. I tried a regular AlertDialog but couldn't get the activity context to be static. I tried adding this to my onDragListener class and to my CustomLayoutClass but it says that getSupportFragmentManager() cannot be referenced from a static method or that it cannot be resolved.
public static void showScoopDialog() {
FragmentManager fm = getSupportFragmentManager();
ScoopSizeDialog editNameDialogFragment = ScoopSizeDialog.newInstance("Some Title");
editNameDialogFragment.show(fm, "fragment_edit_name");
}
This is my custom onDragListener class. I need to show a dialog with edittext when the user drops an image:
public class ChoiceDragListener implements View.OnDragListener {
boolean DEBUG = true;
Context context;
public String TAG = "Drag Layout:";
public ChoiceDragListener(Context context) {
this.context = context;
}
#Override
public boolean onDrag(View v, DragEvent event) {
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
if(DEBUG) Log.v("here","drag started");
break;
case DragEvent.ACTION_DRAG_ENTERED:
break;
case DragEvent.ACTION_DRAG_LOCATION:
int mCurX = (int) event.getX();
int mCurY = (int) event.getY();
if (DEBUG) Log.v("Cur(X, Y) : " ,"here ::" + mCurX + ", " + mCurY );
break;
case DragEvent.ACTION_DRAG_EXITED:
if (DEBUG)
Log.v("here","drag exits");
break;
case DragEvent.ACTION_DROP:
//handle the dragged view being dropped over a drop view
View view = (View) event.getLocalState();
ClipData cd = event.getClipData();
ClipData.Item item = cd.getItemAt(0);
String resp = item.coerceToText(context).toString();
//view dragged item is being dropped on
ImageView dropTarget = (ImageView) v;
//view being dragged and dropped
ImageView dropped = (ImageView) view;
dropped.setEnabled(false);
//if an item has already been dropped here, there will be a tag
Object tag = dropTarget.getTag();
CreateProd.nsList.add(dropped.getTag().toString());
Log.d(TAG, dropped.getTag().toString() + "added to list");
//if there is already an item here, set it back visible in its original place
if (tag != null) {
//the tag is the view id already dropped here
int existingID = (Integer)tag;
//set the original view visible again
((Activity) context).findViewById(existingID).setVisibility(View.VISIBLE);
}
break;
case DragEvent.ACTION_DRAG_ENDED:
if (DEBUG) Log.i("drag event", "ended::" + ChoiceTouchListener.offsetX + "," + ChoiceTouchListener.offsetY);
/**
* returning false so that goes to parentView onDrag function
*/
return false;
//break;
default:
break;
}
return true;
}
}
And this is my custom layout:
public class DragLayout extends RelativeLayout {
boolean DEBUG = true;
AnimationDrawable blenderAnim;
Handler handlerAnim2;
Context context;
private int dimensionInPixel = 200;
int screenWidth,screenHeight;
static float up_x=0,up_y=0;
boolean mIsScrolling = false;
public DragLayout(Context context) {
super(context);
// TODO Auto-generated constructor stub
this.context = context;
//not to include in main program
getDimensionsofScreen();
setLayout();
setViews();
}
private void setLayout() {
// set according to parent layout (not according to current layout)
RelativeLayout.LayoutParams rLp = new RelativeLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
rLp.topMargin = 2 * (screenHeight / 25); // calculating 1/10 of 4/5
// screen
this.setLayoutParams(rLp);
}
void setViews() {
ImageView img2 = new ImageView(context);
int dimensionInDp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dimensionInPixel, getResources().getDisplayMetrics());
RelativeLayout.LayoutParams rLp = new RelativeLayout.LayoutParams(
(screenWidth / 5), (screenHeight / 5));
rLp.topMargin = (screenHeight / 10);
rLp.leftMargin = (4*screenWidth / 10);
rLp.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
img2.setLayoutParams(rLp);
img2.getLayoutParams().height = dimensionInDp;
img2.getLayoutParams().width = dimensionInDp;
img2.setImageDrawable(getResources().getDrawable(R.drawable.blender_anim));
img2.setOnDragListener(new ChoiceDragListener(context));
this.addView(img2);
blenderAnim = (AnimationDrawable)img2.getDrawable();
blenderAnim.setOneShot(true);
blenderAnim.stop();
}
public ArrayList<Integer> getDimensionsofScreen() {
//metrics that holds the value of height and width
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();;
ArrayList<Integer> vals = new ArrayList<Integer>();
vals.add(displayMetrics.widthPixels);
vals.add(displayMetrics.heightPixels);
screenHeight = displayMetrics.heightPixels;
screenWidth = displayMetrics.widthPixels;
return vals;
}
#SuppressLint("NewApi")
#Override
public boolean onDragEvent(DragEvent event) {
int mCurX = (int) event.getX();
int mCurY = (int) event.getY();
if (event.getAction() == DragEvent.ACTION_DRAG_STARTED || event.getAction() == DragEvent.ACTION_DRAG_ENTERED) {
if (blenderAnim.isRunning()) {
blenderAnim.stop();
} else {
blenderAnim.run();
handlerAnim2 = new Handler();
handlerAnim2.postDelayed(
new Runnable() {
#Override
public void run() {
blenderAnim.stop();
}},
getAnimationDuration(blenderAnim));
}
}
if (event.getAction() == DragEvent.ACTION_DROP || event.getAction() == DragEvent.ACTION_DRAG_EXITED) {
if (blenderAnim.isRunning()) {
blenderAnim.stop();
} else {
blenderAnim.run();
handlerAnim2 = new Handler();
handlerAnim2.postDelayed(
new Runnable(){
#Override
public void run() {
blenderAnim.stop();
}},
getAnimationDuration(blenderAnim));
}
Log.v("here", "it is :: " + mCurX + ", " + mCurY);
View view1 = (View) event.getLocalState();
view1.setVisibility(View.VISIBLE);
ObjectAnimator animationx = ObjectAnimator.ofFloat(view1,"translationX", mCurX - ChoiceTouchListener.offsetX-(screenWidth / 10),0.0f);
ObjectAnimator animationy = ObjectAnimator.ofFloat(view1, "translationY", mCurY - ChoiceTouchListener.offsetY - (screenHeight / 10), 0.0f);
AnimatorSet animSet = new AnimatorSet();
animSet.setDuration(500);
animSet.playTogether(animationx,animationy);
animSet.start();
}
if (event.getAction() == DragEvent.ACTION_DROP || event.getAction() == DragEvent.ACTION_DRAG_ENDED){
if (blenderAnim.isRunning()) {
blenderAnim.stop();
}
}
return true;
}
private int getAnimationDuration(AnimationDrawable src) {
int dur = 0;
for (int i = 0; i<src.getNumberOfFrames(); i++) {
dur += src.getDuration(i);
}
return dur;
}
private void showScoopDialog() {
FragmentManager fm = getSupportFragmentManager();
ScoopSizeDialog editNameDialogFragment = ScoopSizeDialog.newInstance("Some Title");
editNameDialogFragment.show(fm, "fragment_edit_name");
}
}

Adding textviews dynamically to relativelayout.

While I am adding textviews to relative layout, at the end of first line, the textview is going wrong.
as shown in below:
.
here is my code to diplay textviews.
public void showkeyword()
{
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout fl = (RelativeLayout)findViewById(R.id.key_layout);
fl.removeAllViews();
RelativeLayout.LayoutParams params ;
//TextView key = (TextView) inflater.inflate(R.layout.tag_keyword,null);
i = 0;
for(String s : alist)
{
TextView textview = (TextView) inflater.inflate(R.layout.tag_keyword,null);
textview.setText(s);
textview.setId(2000 + i);
if (i == 0) {
RelativeLayout.LayoutParams rlp2 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
rlp2.addRule(RelativeLayout.ALIGN_PARENT_TOP);
rlp2.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
textview.setLayoutParams(rlp2);
fl.addView(textview);
} else {
RelativeLayout.LayoutParams rlp2 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
// rlp2.addRule(RelativeLayout.ALIGN_BASELINE);
rlp2.setMargins(10,0, 10,0);
rlp2.addRule(RelativeLayout.RIGHT_OF, textview.getId() - 1);
textview.setLayoutParams(rlp2);
fl.addView(textview);
}
i++;
}
}
I wish to have something like this, sort of a tab implementation:
Hope the following code will help you out:
Functioning:
contactWrapper is a linear layout, we go on adding the textviews into these linear layouts one by one and before adding find whether the contactWrapper has space enough to put in the next TextView, if not a new linear layout is created and the textViews are added into it.
Take time analyzing the following code.
public void drawLayout() {
int counter = 0;
contactWrapperWidth = getResources().getDisplayMetrics().widthPixels;
contactWrapper.setOrientation(LinearLayout.VERTICAL);
// contact wrapper is a linear Layout
// use LinearLayout contactWrapper = (LinearLayout) mView
// .findViewById(R.id.yourLinearLayout);
currCounter = 0;
currWidth = 0;
isNewLine = false;
row[currCounter] = new LinearLayout(getActivity());
#SuppressWarnings("rawtypes")
Iterator it = button.iterator();
for (int i = 0; i < button.size(); i++) {
it.next();
row[currCounter].setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
currWidth += Integer
.parseInt(button.get(i).get("width").toString());
Log.i("Item width ", "i == "
+ button.get(i).get("width").toString());
// contactWrapper.getw
if (isNewLine) {
if (currWidth < contactWrapperWidth) {
row[currCounter]
.addView((View) button.get(i).get("button"));
if (!it.hasNext()) {
contactWrapper.addView(row[currCounter]);
} else {
if (contactWrapperWidth < (currWidth + Integer
.parseInt(button.get(i + 1).get("width")
.toString()))) {
isNewLine = true;
contactWrapper.addView(row[currCounter]);
currCounter += 1;
row[currCounter] = new LinearLayout(getActivity());
currWidth = 0;
} else {
isNewLine = false;
}
}
} else {
isNewLine = true;
contactWrapper.addView(row[currCounter]);
currCounter += 1;
row[currCounter] = new LinearLayout(getActivity());
currWidth = 0;
}
} else {
if (currWidth < contactWrapperWidth) {
if (!it.hasNext()) {
View view = (View) button.get(i).get("button");
row[currCounter].addView((View) button.get(i).get(
"button"));
contactWrapper.addView(row[currCounter]);
} else {
View view = (View) button.get(i).get("button");
row[currCounter].addView((View) button.get(i).get(
"button"));
if (contactWrapperWidth < (currWidth + Integer
.parseInt(button.get(i + 1).get("width")
.toString()))) {
isNewLine = true;
Logger.show(Log.INFO, "it.hasNext()",
"it.hasNext() contactWrapper");
contactWrapper.addView(row[currCounter]);
currCounter += 1;
row[currCounter] = new LinearLayout(getActivity());
currWidth = 0;
} else {
isNewLine = false;
}
}
} else {
isNewLine = true;
contactWrapper.addView(row[currCounter]);
currCounter += 1;
row[currCounter] = new LinearLayout(getActivity());
currWidth = 0;
}
}
counter++;
}
}
Finally I am able to remove that bug using idea by #kailas
Here I am posting my method:
public void showkeyword() {
int counter = 0;
int screenWidth = getResources().getDisplayMetrics().widthPixels;
final RelativeLayout contactWrapper = (RelativeLayout)findViewById(R.id.key_layout);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout.LayoutParams buttonparams = new RelativeLayout.LayoutParams(
150,
80);
int i = 0;
contactWrapper.removeAllViews();
// contact wrapper is a linear Layout
// use LinearLayout contactWrapper = (LinearLayout) mView
// .findViewById(R.id.yourLinearLayout);
int currCounter = 0;
int currWidth = 0;
boolean isNewLine = false;
boolean firstLine = true;
for(final String s : alist)
{
TextView textview = new TextView(this);
RelativeLayout.LayoutParams rlp1 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
rlp1.setMargins(7, 5, 7, 0);
textview.setText(s);
textview.setId(2000 + i);
textview.setBackgroundColor(Color.DKGRAY);
textview.setTextColor(Color.CYAN);
textview.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
contactWrapper.removeView(v);
alist.remove(s);
}
});
int width = s.length()*15;
if((currWidth+width+150)<=screenWidth)
{
currWidth += width+10;
isNewLine = false;
currCounter++;
}
else{
currWidth = width+14;
firstLine = false ;
isNewLine = true;
currCounter=1;
}
if(i==0)
{ rlp1.addRule(RelativeLayout.ALIGN_START);
textview.setLayoutParams(rlp1);
contactWrapper.addView(textview);
}
else if(isNewLine){
rlp1.addRule(RelativeLayout.ALIGN_LEFT);
rlp1.addRule(RelativeLayout.BELOW,2000-1+i );
textview.setLayoutParams(rlp1);
contactWrapper.addView(textview);
}
else if(firstLine)
{
rlp1.addRule(RelativeLayout.RIGHT_OF,2000-1+i );
textview.setLayoutParams(rlp1);
contactWrapper.addView(textview);
}
else{
rlp1.addRule(RelativeLayout.RIGHT_OF,2000-1+i );
rlp1.addRule(RelativeLayout.BELOW,2000-currCounter+i );
textview.setLayoutParams(rlp1);
contactWrapper.addView(textview);
}
i++;
}
buttonparams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
buttonparams.addRule(RelativeLayout.ALIGN_BASELINE,2000-1+i);
Button clearbtn = new Button(this);
clearbtn.setText("clear");
// clearbtn.setBackgroundColor(Color.RED);
// clearbtn.setTextColor(Color.CYAN);
clearbtn.setLayoutParams(buttonparams);
clearbtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
contactWrapper.removeAllViews();
alist.clear();
}
});
contactWrapper.addView(clearbtn) ;
}
Try to remove
rlp2.addRule(RelativeLayout.ALIGN_PARENT_TOP);
rlp2.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
because the behavior you want is the default behavior.
Put Orientation horinzontal in the relative layout.
Try using a LinearLayout and a fixed height (using the dip unit) instead of WRAP_CONTENT
Try to put all the text you want in one String and then put all this text in only one TextView.
The best way is using StringBuilder to concat the text:
StringBuilder sb = new StringBuilder();
sb.append("str1");
sb.append("str2");
and then put the string in the textview
textview.setText(sb.toString());

Touch listener and changing parent

I apologize for my English. I have a problem.
I use a listeners LongClick and TouchListener.
In the long click - the view is removed and the parent view is inserted into the other parent.
Touch stops working, because there was a change parent.
How do I keep TouchListener to View?
static boolean drag = false;
static View parent;
static OnLongClickListener olcl = new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
if(!drag) {
parent = (View) v.getParent();
int[] loc = {0, 0};
v.getLocationOnScreen(loc);
((ViewGroup) parent).removeView(v);
Main.mainRelative.addView(v);
RelativeLayout.LayoutParams par = (LayoutParams) v.getLayoutParams();
par.leftMargin = loc[0];
par.topMargin = loc[1];
v.setLayoutParams(par);
drag = true;
return true;
}
return false;
}
};
static OnTouchListener otl = new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(v.getParent() != null && v.getParent() == Main.mainRelative) {
//!!!!!!!!!!!!!
RelativeLayout.LayoutParams par = (LayoutParams) v.getLayoutParams();
par.leftMargin = (int) (event.getRawX() - v.getWidth()/2);
par.topMargin = (int) (event.getRawY() - v.getHeight()/1.2);
v.setLayoutParams(par);
for(int y = 0; y < Main.radioGroupLeftMain.getChildCount(); y++) {
RadioButton rb = (RadioButton) ((ViewGroup) Main.radioGroupLeftMain.getChildAt(y)).getChildAt(0);
if(checkHit((int)event.getRawX(), (int)event.getRawY(), rb)) {
rb.setChecked(true);
} else {
rb.setChecked(false);
}
if(event.getAction() == MotionEvent.ACTION_UP) {
try { ((ViewGroup) v.getParent()).removeView(v); } catch(Exception e) {};
if(v.getVisibility() == View.VISIBLE) {
((ViewGroup) parent).addView(v);
}
drag = false;
}
}
}
return false;
}
};
public static boolean checkHit(int x, int y, View v) {
int[] loc = {0, 0};
v.getLocationOnScreen(loc);
Rect rv = new Rect(loc[0], loc[1], loc[0]+v.getWidth(), loc[1]+v.getHeight());
return rv.contains(x, y);
}
when your are going to add view Main.mainRelative.addView(v);
before this create new View, initialize with this view v like View vv = v
then again set touch listener vv.setOnTouchLIstener(ot1);
try this it should work...

Horizontal scroll view scrolling one item at time

i am currently implementing a panel that include horizontal list view using Horizontal scroll view . in that I need control the scrolling of Horizontal scroll view and do the scrolling one item at time.
could any one give me idea to do this kind of thing.
I manged to do this using overriding HorizontalScrollView and merging code i got from various internet examples .it is working fine .
i have used gestureDetector and onFling method to achieve this task.
public void setCenter(int index) {
ViewGroup parent = (ViewGroup) getChildAt(0);
View preView = parent.getChildAt(prevIndex);
//preView.setBackgroundColor(Color.parseColor("#64CBD8"));
android.widget.LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(5, 0, 5, 0);
preView.setLayoutParams(lp);
View view = parent.getChildAt(index);
//view.setBackgroundColor(Color.RED);
int screenWidth = ((Activity) context).getWindowManager()
.getDefaultDisplay().getWidth();
int scrollX = (view.getLeft() - (screenWidth / 2))
+ (view.getWidth() / 2);
this.smoothScrollTo(scrollX, 0);
prevIndex = index;
Log.d("ITEM", String.valueOf(prevIndex));
}
#Override
public boolean onDown(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
if (flingDisable)
return false;
boolean returnValue = false;
float ptx1 = 0, ptx2 = 0;
if (e1 == null || e2 == null)
return false;
ptx1 = e1.getX();
ptx2 = e2.getX();
// right to left
if (ptx1 - ptx2 > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
if (activeItem < maxItem - 1)
activeItem = activeItem + 1;
returnValue = true;
} else if (ptx2 - ptx1 > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
if (activeItem > 0)
activeItem = activeItem - 1;
returnValue = true;
}
//scrollTo = activeItem * itemWidth;
//this.smoothScrollTo(0, scrollTo);
setCenter(activeItem);
return returnValue;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (gestureDetector.onTouchEvent(event)) {
return true;
}
Boolean returnValue = gestureDetector.onTouchEvent(event);
int x = (int) event.getRawX();
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
if (start) {
this.prevScrollX = x;
start = false;
}
break;
case MotionEvent.ACTION_UP:
start = true;
this.currentScrollX = x;
int minFactor = itemWidth / SWIPE_PAGE_ON_FACTOR;
if ((this.prevScrollX - this.currentScrollX) > minFactor) {
if (activeItem < maxItem - 1)
activeItem = activeItem + 1;
} else if ((this.currentScrollX - this.prevScrollX) > minFactor) {
if (activeItem > 0)
activeItem = activeItem - 1;
}
Log.d("ITEM", String.valueOf(activeItem));
setCenter(activeItem);
returnValue = true;
break;
}
return returnValue;
}

Categories