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>
Related
I am trying to make TextView which moves across the screen in all directions randomly using translateAnimation. I need text moving like in screen saver for example going round and round until it is clicked.But have some problems:
1. text moves just from top to bottom
2.it doesn't stop in screen borders , it is going off the screen then coming back again :
public class aktivityStarted extends AppCompatActivity {
TextView textMovin;
/* int loc[]=new int[2];
int x=loc[0];
int y=loc[1];*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_aktivity_started);
textMovin=findViewById(R.id.movingText);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
final int width = displaymetrics.widthPixels-textMovin.getWidth();
final int height = displaymetrics.heightPixels-textMovin.getHeight();
final Random r = new Random();
final int translationX = r.nextInt(width);
final int translationY = r.nextInt(height);
final int randomx=r.nextInt(50)+1;
final int randomy=r.nextInt(50)+1;
final TranslateAnimation anim = new TranslateAnimation(-translationX,translationX ,-translationY,translationY ); //Use current view position instead of `currentX` and `currentY`
anim.setDuration(2500);
anim.setRepeatCount(-1);
anim.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
anim.reset();
anim.setRepeatMode(Animation.REVERSE);
anim.setFillAfter(true);
}
#Override
public void onAnimationRepeat(Animation animation) {
textMovin.setY(r.nextInt(height));
textMovin.setX(r.nextInt(width));
anim.start();
}
});
textMovin.startAnimation(anim);
}
}
try this code:
public class MainActivity extends AppCompatActivity {
private View parent;
private TextView textMovin;
private float speedX;
private float speedY;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textMovin = findViewById(R.id.textV);
parent = findViewById(R.id.parent);
final Random r = new Random();
speedX = r.nextFloat() * 200;
speedY = r.nextFloat() * 200;
parent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
final int width = parent.getWidth() - textMovin.getWidth();
final int height = parent.getHeight() - textMovin.getHeight();
final int period = 50;
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
textMovin.post(new TimerTask() {
#Override
public void run() {
textMovin.setX(speedX * period / 1000.0f + textMovin.getX());
textMovin.setY(speedY * period / 1000.0f + textMovin.getY());
if (textMovin.getY() <= 0 || textMovin.getY() >= height)
speedY *= -1;
if (textMovin.getX() <= 0 || textMovin.getX() >= width)
speedX *= -1;
}
});
}
}, 50, period);
}
});
findViewById(R.id.random).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Random r = new Random();
speedX = r.nextFloat() * 200;
speedY = r.nextFloat() * 200;
}
});
}
}
and the layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/textV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Hello World!" />
<Button
android:id="#+id/random"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="10dp"
android:text="Random" />
</RelativeLayout>
Hope it works for you.
public class OnDragTouchListener implements View.OnTouchListener {
/**
* Callback used to indicate when the drag is finished
*/
public interface OnDragActionListener {
/**
* Called when drag event is started
*
* #param view The view dragged
*/
void onDragStart(View view);
/**
* Called when drag event is completed
*
* #param view The view dragged
*/
void onDragEnd(View view);
}
private View mView;
private View mParent;
private boolean isDragging;
private boolean isInitialized = false;
private int width;
private float xWhenAttached;
private float maxLeft;
private float maxRight;
private float dX;
private int height;
private float yWhenAttached;
private float maxTop;
private float maxBottom;
private float dY;
private OnDragActionListener mOnDragActionListener;
public OnDragTouchListener(View view) {
this(view, (View) view.getParent(), null);
}
public OnDragTouchListener(View view, View parent) {
this(view, parent, null);
}
public OnDragTouchListener(View view, OnDragActionListener onDragActionListener) {
this(view, (View) view.getParent(), onDragActionListener);
}
public OnDragTouchListener(View view, View parent, OnDragActionListener onDragActionListener) {
initListener(view, parent);
setOnDragActionListener(onDragActionListener);
}
public void setOnDragActionListener(OnDragActionListener onDragActionListener) {
mOnDragActionListener = onDragActionListener;
}
public void initListener(View view, View parent) {
mView = view;
mParent = parent;
isDragging = false;
isInitialized = false;
}
public void updateBounds() {
updateViewBounds();
updateParentBounds();
isInitialized = true;
}
public void updateViewBounds() {
width = mView.getWidth();
xWhenAttached = mView.getX();
dX = 0;
height = mView.getHeight();
yWhenAttached = mView.getY();
dY = 0;
}
public void updateParentBounds() {
maxLeft = 0;
maxRight = maxLeft + mParent.getWidth();
maxTop = 0;
maxBottom = maxTop + mParent.getHeight();
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (isDragging) {
float[] bounds = new float[4];
// LEFT
bounds[0] = event.getRawX() + dX;
if (bounds[0] < maxLeft) {
bounds[0] = maxLeft;
}
// RIGHT
bounds[2] = bounds[0] + width;
if (bounds[2] > maxRight) {
bounds[2] = maxRight;
bounds[0] = bounds[2] - width;
}
// TOP
bounds[1] = event.getRawY() + dY;
if (bounds[1] < maxTop) {
bounds[1] = maxTop;
}
// BOTTOM
bounds[3] = bounds[1] + height;
if (bounds[3] > maxBottom) {
bounds[3] = maxBottom;
bounds[1] = bounds[3] - height;
}
switch (event.getAction()) {
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
onDragFinish();
break;
case MotionEvent.ACTION_MOVE:
mView.animate().x(bounds[0]).y(bounds[1]).setDuration(0).start();
break;
}
return true;
} else {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
isDragging = true;
if (!isInitialized) {
updateBounds();
}
dX = v.getX() - event.getRawX();
dY = v.getY() - event.getRawY();
if (mOnDragActionListener != null) {
mOnDragActionListener.onDragStart(mView);
}
return true;
}
}
return false;
}
private void onDragFinish() {
if (mOnDragActionListener != null) {
mOnDragActionListener.onDragEnd(mView);
}
dX = 0;
dY = 0;
isDragging = false;
}
}
And you can set it using:
myView.setOnTouchListener(new OnDragTouchListener(myView));
Or by adding this directly in init method of your Custom View:
setOnTouchListener(new OnDragTouchListener(this));
this my xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:gravity="center"
>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:elevation="0dp">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
style="#style/custom_toolbar"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.AppBarLayout>
<RelativeLayout
android:id="#+id/layout_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="#ffffff" />
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="12"
>
<RelativeLayout
android:id="#+id/ec_rltabselected"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp" >
<AbsoluteLayout
android:id="#+id/relative1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/border_rounding" >
<ImageView
android:id="#+id/ivCardView"
android:layout_width="fill_parent"
android:layout_height="match_parent" />
</AbsoluteLayout>
</RelativeLayout>
<LinearLayout
android:id="#+id/llBottomLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_margin="5dp"
android:orientation="horizontal"
android:padding="5dp"
android:weightSum="0" >
</LinearLayout>
</FrameLayout>
<android.support.v7.widget.RecyclerView
android:layout_weight="1"
android:layout_marginBottom="10dp"
android:id="#+id/recyclerview_up"
android:layout_width="match_parent"
android:layout_height="150dp"
/>
</LinearLayout>
And my class :
public class clothe_codi extends AppCompatActivity {
private Toolbar toolbar;
ArrayList<String> arr_id_list;
Clothe_DBHelper helper;
SQLiteDatabase db;
List<clothe_codi_mini_item> codi;
RecyclerView recyclerView_mini_codi;
//경계선
private Button m_btnSelectImage, m_btnSDeleteImage, m_btnZoom;
private Context m_context;
private LinearLayout m_llTopLayout;
private ImageView m_ivImage, m_ivtmpImage;
private Display m_screen;
private int m_DisplayWidth, m_ImageCount, m_viewsAddedHeightEmotions = 0,
m_height, m_absHeight = 0, m_AddedViewsHeightText = 0,
m_deleteEditHeightwidth;
private Dialog m_dialog;
private View.OnTouchListener m_touchImagListener, m_strecthArrowListener;
private AbsoluteLayout m_absolutelayout, m_absTextlayout, m_absZoomlayout;
private int m_widthDelete = 0, m_totalTextViewCount = 0;
private float m_oldDist = 1f, m_scale, m_oldX = 0, m_oldY = 0, m_dX, m_dY,
m_posX, m_posY, m_prevX = 0, m_prevY = 0, m_newX, m_newY;
ViewTreeObserver m_vtoTree;
private AbsoluteLayout.LayoutParams m_layoutparams, m_layoutparamsDelete,
m_layoutParamsEdit;
private ArrayList<ViewsVo> m_arrSignObjects;
private Bitmap m_bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.clothe_codi);
//id데리고 오기
arr_id_list = new ArrayList<String>();
//db만들기
helper = new Clothe_DBHelper(getApplicationContext());
db = helper.getWritableDatabase();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationIcon(R.drawable.ref_back);
//toolbar상단에 글씨설정
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("코디하기");
recyclerView_mini_codi=(RecyclerView)findViewById(R.id.recyclerview_up);
LinearLayoutManager layoutManager_up=new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
recyclerView_mini_codi.setHasFixedSize(true);
recyclerView_mini_codi.setLayoutManager(layoutManager_up);
codi=new ArrayList<>();
//listview에 뿌려주기 위하여
ClotheSelect();
recyclerView_mini_codi.setAdapter(new clothe_codi_mini_item_RecyclerAdapter(getApplicationContext(),codi,R.layout.activity_main));
recyclerView_mini_codi.addOnItemTouchListener(new RecyclerViewOnItemClickListener(this, recyclerView_mini_codi,
new RecyclerViewOnItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View v, int position) {
final Integer selectedPos = position;
String popo = arr_id_list.get(selectedPos);
Cursor search;
search = db.rawQuery("SELECT * FROM clothe_list where _id = '" + popo + "';", null);
while (search.moveToNext()){
byte[] byteimage = search.getBlob(3);
Bitmap bitmapimage = DbBitmapUtility.getBitmap(byteimage);
getImageLayout(bitmapimage);
}
search.close();
}
#Override
public void onItemLongClick(View v, int position) {
}
}
));
//I made Drag and Drop to Move Objects on Finger Touch in Android
m_context = clothe_codi.this;
m_ivImage = (ImageView) findViewById(R.id.ivCardView);
m_absolutelayout = (AbsoluteLayout) findViewById(R.id.relative1);
m_llTopLayout = (LinearLayout) findViewById(R.id.llBottomLayout);
m_arrSignObjects = new ArrayList<ViewsVo>();
// Set the layout parameters to the Absolute layout for adding images.
RelativeLayout.LayoutParams rl_pr = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.FILL_PARENT);
rl_pr.addRule(RelativeLayout.ABOVE, R.id.llBottomLayout);
rl_pr.addRule(RelativeLayout.BELOW, R.id.layout_title);
m_absolutelayout.setLayoutParams(rl_pr);
m_screen = ((WindowManager) getSystemService(WINDOW_SERVICE))
.getDefaultDisplay();
m_DisplayWidth = m_screen.getWidth();
m_AddedViewsHeightText = m_llTopLayout.getHeight();
// Get the absoulte layout height according to the device screen density
// to set the layout.
m_vtoTree = m_absolutelayout.getViewTreeObserver();
m_vtoTree.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
m_absHeight = m_absolutelayout.getHeight();
m_absolutelayout.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
}
});
m_dialog = new Dialog(this, R.style.Dialog);
m_dialog.setCancelable(true);
}
public void ClotheSelect() {
Cursor search;
search = db.rawQuery("SELECT * FROM clothe_list", null);
while (search.moveToNext()){
String up_down = search.getString(1);
String clothename = search.getString(2);
byte[] byteimage = search.getBlob(3);
Bitmap bitmapimage = DbBitmapUtility.getBitmap(byteimage);
codi.add(new clothe_codi_mini_item(up_down, clothename, bitmapimage));
//id를 저장
arr_id_list.add(search.getString(0));
}
search.close();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case android.R.id.home:
// NavUtils.navigateUpFromSameTask(this) 를 사용할 경우 모든 Activity를 Destroy 시키고 부모 Activity로 돌아간다.
// NavUtils.navigateUpFromSameTask(this);
// finish() 를 사용할 경우 현재 Activity를 Destroy하고 부모 Activity로 돌아간다.
finish();
return true;
case R.id.setting:
Intent timesetting = new Intent(clothe_codi.this, ref_time_setting.class);
startActivity(timesetting);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 0:
if (requestCode == 0 && resultCode == RESULT_OK && null != data) {
m_bitmap = null;
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
m_bitmap = BitmapFactory.decodeFile(picturePath);
getImageLayout(m_bitmap);
}
break;
}
}
/**
* Method to set the view's height dynamically according to screen size.
*/
private void setViewsHeightDynamically() {
if (m_absHeight <= 500) {
m_layoutparamsDelete = new AbsoluteLayout.LayoutParams(20, 20, 110,0);
m_layoutParamsEdit = new AbsoluteLayout.LayoutParams(20, 20, 110,110);
m_deleteEditHeightwidth = 20;
} else if (m_absHeight >= 900) {
m_layoutparamsDelete = new AbsoluteLayout.LayoutParams(40, 40, 130,0);
m_layoutParamsEdit = new AbsoluteLayout.LayoutParams(40, 40, 130,130);
m_deleteEditHeightwidth = 40;
} else {
m_layoutparamsDelete = new AbsoluteLayout.LayoutParams(35, 35, 140,0);
m_layoutParamsEdit = new AbsoluteLayout.LayoutParams(35, 35, 120,120);
m_deleteEditHeightwidth = 35;
}
}
/**
* Method to add the image by setting and creating the views dynamically
* with delete and zoom option.
*/
#SuppressWarnings("deprecation")
private void getImageLayout(Bitmap p_bitmap) {
ViewsVo m_signVo;
//Check for images count .Set the count for limiting the number of images to add on screen.
if (m_ImageCount < 1) {
m_viewsAddedHeightEmotions = m_viewsAddedHeightEmotions + 90;
m_ImageCount++;
}
m_btnSDeleteImage = new Button(m_context);
m_btnZoom = new Button(m_context);
m_ivtmpImage = new ImageView(m_context);
setViewsHeightDynamically();
m_btnSDeleteImage.setLayoutParams(m_layoutparamsDelete);
m_btnSDeleteImage.setBackgroundDrawable(getResources().getDrawable(
R.drawable.ic_deletered));
m_btnSDeleteImage.setId(0);
m_btnSDeleteImage.setOnClickListener(new ImageDeleteListener());
m_btnZoom.setLayoutParams(m_layoutParamsEdit);
m_btnZoom.setBackgroundDrawable(getResources().getDrawable(
R.drawable.right_arrow));
m_btnZoom.setId(0);
m_absTextlayout = new AbsoluteLayout(m_context);
m_absZoomlayout = new AbsoluteLayout(m_context);
//500여기 숫자를 늘리면 이미지 자체 화질이 좋아진다.
m_ivtmpImage.setImageBitmap(Bitmap.createScaledBitmap(p_bitmap, 500, 500, true));
m_absTextlayout.setLayoutParams(new AbsoluteLayout.LayoutParams(AbsoluteLayout.LayoutParams.WRAP_CONTENT,AbsoluteLayout.LayoutParams.WRAP_CONTENT, 0, 0));
m_absZoomlayout.setLayoutParams(new AbsoluteLayout.LayoutParams(AbsoluteLayout.LayoutParams.WRAP_CONTENT,AbsoluteLayout.LayoutParams.WRAP_CONTENT, 0, 0));
if (m_absHeight >= 900)
//setLayoutParams를 이용하여 위의 이미지 크기를 지정한다.
m_ivtmpImage.setLayoutParams(new FrameLayout.LayoutParams(100, 100));
else
m_ivtmpImage.setLayoutParams(new FrameLayout.LayoutParams(80, 80));
m_ivtmpImage.setBackgroundColor(Color.TRANSPARENT);
m_absTextlayout.addView(m_btnSDeleteImage);
if (m_absHeight >= 900)
m_absZoomlayout.setPadding(20, 20, 15, 15);
else
m_absZoomlayout.setPadding(15, 15, 15, 15);
/*m_absZoomlayout.setBackgroundResource(R.drawable.dashedbordersmall);*/
m_absZoomlayout.addView(m_ivtmpImage);
m_absTextlayout.addView(m_absZoomlayout);
m_absTextlayout.addView(m_btnZoom);
m_absTextlayout.setDrawingCacheEnabled(true);
m_absTextlayout.setClickable(true);
m_absTextlayout.setId(0);
m_ivtmpImage.setId(0);
m_vtoTree =m_absTextlayout.getViewTreeObserver();
m_vtoTree.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
m_absTextlayout.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
}
});
/**
* Add all the views into arraylist which are added into the screen for
* further to perform deletion of each views.
*/
m_signVo = new ViewsVo();
m_arrSignObjects.add(0, m_signVo);
m_absolutelayout.addView(m_absTextlayout);
// Image touch listener to move image onTouch event on screen.
m_touchImagListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
m_oldX = event.getX();
m_oldY = event.getY();
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
break;
case MotionEvent.ACTION_MOVE:
m_dX = event.getX() - m_oldX;
m_dY = event.getY() - m_oldY;
m_posX = m_prevX + m_dX;
m_posY = m_prevY + m_dY;
if (m_posX > 0 && m_posY > 0&& (m_posX + v.getWidth()) < m_absolutelayout.getWidth()&& (m_posY + v.getHeight()) < m_absolutelayout.getHeight())
{
v.setLayoutParams(new AbsoluteLayout.LayoutParams(v.getMeasuredWidth(), v.getMeasuredHeight(),(int) m_posX, (int) m_posY));
m_prevX = m_posX;
m_prevY = m_posY;
}
break;
}
return false;
}
};
// Listener for the arrow ontouch of arrow ZoomIn and ZoomOut the image.
m_strecthArrowListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
View view;
view = v;
v.setClickable(true);
v.setDrawingCacheEnabled(true);
AbsoluteLayout m_absLayout = null;
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
m_oldX = event.getX();
m_oldY = event.getY();
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
break;
case MotionEvent.ACTION_MOVE:
m_newX = event.getX();
m_newY = event.getY();
float newDist = m_newX - m_oldX;
if (m_newX > m_oldX && m_newY > m_oldY) {
if (newDist > 0.0f) {
m_scale = 1;
m_absLayout = (AbsoluteLayout) v.getParent();
int m_hightOfImage = (int) (m_scale + (((ImageView) ((AbsoluteLayout) m_absLayout.getChildAt(1)).getChildAt(0)).getHeight()));
int m_widthOfImage = (int) (m_scale + (((ImageView) ((AbsoluteLayout) m_absLayout.getChildAt(1)).getChildAt(0)).getWidth()));
m_widthDelete = (int) (m_scale + ((((AbsoluteLayout) m_absLayout.getChildAt(1))).getWidth()));
if (m_absLayout.getBottom() <= (m_ivImage.getBottom())
&& m_absLayout.getRight() <= (m_DisplayWidth)) {
m_layoutparams = new AbsoluteLayout.LayoutParams( m_widthOfImage, m_hightOfImage, 0, 0);
((ImageView) ((AbsoluteLayout) m_absLayout.getChildAt(1)).getChildAt(0)).setLayoutParams(m_layoutparams);
m_layoutparams = new AbsoluteLayout.LayoutParams( AbsoluteLayout.LayoutParams.WRAP_CONTENT,AbsoluteLayout.LayoutParams.WRAP_CONTENT,m_absLayout.getLeft(), m_absLayout.getTop());
m_absLayout.setLayoutParams(m_layoutparams);
((Button) m_absLayout.getChildAt(0)).setLayoutParams(new AbsoluteLayout.LayoutParams(m_deleteEditHeightwidth,m_deleteEditHeightwidth,m_widthDelete, 0));
((Button) m_absLayout.getChildAt(2)).setLayoutParams(new AbsoluteLayout.LayoutParams(m_deleteEditHeightwidth,m_deleteEditHeightwidth,m_widthDelete, m_widthDelete));
m_hightOfImage = (int) (m_scale + (((AbsoluteLayout) m_absLayout.getChildAt(1)).getHeight()));
m_widthOfImage = (int) (m_scale + (((AbsoluteLayout) m_absLayout.getChildAt(1)).getWidth()));
m_layoutparams = new AbsoluteLayout.LayoutParams( m_widthOfImage, m_hightOfImage,((AbsoluteLayout) m_absLayout .getChildAt(1)).getLeft(),((AbsoluteLayout) m_absLayout .getChildAt(1)).getTop());
((AbsoluteLayout) m_absLayout.getChildAt(1)).setLayoutParams(m_layoutparams);
}
}
}
if (m_newX < m_oldX && m_newY < m_oldY) {
m_absLayout = (AbsoluteLayout) view.getParent();
int m_hightOfImage = (int) (((ImageView) ((AbsoluteLayout) m_absLayout.getChildAt(1)).getChildAt(0)).getHeight() - m_scale);
int m_widthOfImage = (int) (((ImageView) ((AbsoluteLayout) m_absLayout.getChildAt(1)).getChildAt(0)).getWidth() - m_scale);
m_widthDelete = (int) (((AbsoluteLayout) m_absLayout.getChildAt(1)).getWidth() - m_scale);
m_layoutparams = new AbsoluteLayout.LayoutParams( m_widthOfImage, m_hightOfImage, 0, 0);
((ImageView) ((AbsoluteLayout) m_absLayout.getChildAt(1)).getChildAt(0)).setLayoutParams(m_layoutparams);
m_layoutparams = new AbsoluteLayout.LayoutParams(
AbsoluteLayout.LayoutParams.WRAP_CONTENT,
AbsoluteLayout.LayoutParams.WRAP_CONTENT,
m_absLayout.getLeft(), m_absLayout.getTop());
m_absLayout.setLayoutParams(m_layoutparams);
((Button) m_absLayout.getChildAt(0)).setLayoutParams(new AbsoluteLayout.LayoutParams(m_deleteEditHeightwidth,
m_deleteEditHeightwidth, m_widthDelete,0));
((Button) m_absLayout.getChildAt(2)).setLayoutParams(new AbsoluteLayout.LayoutParams(m_deleteEditHeightwidth,
m_deleteEditHeightwidth, m_widthDelete,m_widthDelete));
m_hightOfImage = (int) ((((AbsoluteLayout) m_absLayout
.getChildAt(1)).getHeight()) - m_scale);
m_widthOfImage = (int) ((((AbsoluteLayout) m_absLayout
.getChildAt(1)).getWidth()) - m_scale);
m_layoutparams = new AbsoluteLayout.LayoutParams(
m_widthOfImage, m_hightOfImage, ((AbsoluteLayout) m_absLayout.getChildAt(1)).getLeft(),((AbsoluteLayout) m_absLayout.getChildAt(1)).getTop());
((AbsoluteLayout) m_absLayout.getChildAt(1))
.setLayoutParams(m_layoutparams);
}
break;
}
return false;
}
};
m_absTextlayout.setOnTouchListener(m_touchImagListener);
m_btnZoom.setOnTouchListener(m_strecthArrowListener);
}
// Delete button listener to show the alert and confirmation for deleting
// the items.
private class ImageDeleteListener implements View.OnClickListener {
#Override
public void onClick(final View v) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
m_context);
alertDialogBuilder.setTitle("Drag & Drop");
alertDialogBuilder
.setMessage("Are you sure you want to delete ?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
m_ImageCount--;
for (int counter = 0; counter < m_arrSignObjects
.size(); counter++) {
if (v.getId() == m_arrSignObjects.get(counter).getViewId()) {
if (m_totalTextViewCount <= 0) {
m_AddedViewsHeightText = m_AddedViewsHeightText
- m_arrSignObjects.get(counter).getViewHeight();
} else {
m_totalTextViewCount--;
}
m_absolutelayout.removeView((View) v
.getParent());
m_arrSignObjects.remove(counter);
break;
}
}
}
}).setNegativeButton("No",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,
int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
}
}
I made Drag and Drop to Move Objects on Finger Touch in Android
Reference site this : http://grishma102.blogspot.kr/2013/10/drag-and-drop-functionality-to-move.html
But, my activity's zoom in, zoom out don't function
When I move objects on Finger Touch, the objects just zoom out and screen out.
please help me..
Try overriding OnDrag() listener instead of onTouch()
view.setOnDragListener(new View.OnDragListener() {
#Override
public boolean onDrag(View view, DragEvent dragEvent) {
return true;
}
});
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>
I am developing an application in which I am using Drag and Drop functionality.
In that I am generating buttons OnClick.The code is working fine but when I drag the button to the corners of the relativelayout,button gets out of the layout. I want it to stay inside of the layout.
Before Dragging the button
After Dragging the button (on top corner in this example)
As you can see that the button is getting out of the layout whenever I drag it towards the end/corner of the layout, I want it to stay in the layout intact, display full button. How can I do that?
Thanks in advance.!
MainActivity.java
public class MainActivity extends Activity implements OnTouchListener {
Button btnAddButton;
RelativeLayout rl1;
int i = 1;
private int _xDelta;
private int _yDelta;
ViewGroup _root;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAddButton = (Button) findViewById(R.id.btnAdd);
rl1 = (RelativeLayout) findViewById(R.id.relative_layout);
_root = (ViewGroup)findViewById(R.id.relative_layout);
btnAddButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
add(v);
}
});
}
public void add(View v) {
Button btn = new Button(MainActivity.this);
//btn.setId(i);
RelativeLayout.LayoutParams layoutParam = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
int a=(int) (Math.random()*100);
// Toast.makeText(MainActivity.this, String.valueOf(Math.random()*100), 1).show();//double a=Math.random();
layoutParam.leftMargin = 30+a;
if (i > 1) {
layoutParam.addRule(RelativeLayout.BELOW, (i - 1));
}
btn.setText("Button" + i);
rl1.addView(btn, layoutParam);
btn.setOnTouchListener(this);
i++;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
final int X = (int) event.getRawX();
final int Y = (int) event.getRawY();
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) v.getLayoutParams();
_xDelta = X - lParams.leftMargin;
_yDelta = Y - lParams.topMargin;
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_POINTER_DOWN:
break;
case MotionEvent.ACTION_POINTER_UP:
break;
case MotionEvent.ACTION_MOVE:
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) v.getLayoutParams();
layoutParams.leftMargin = X - _xDelta;
layoutParams.topMargin = Y - _yDelta;
layoutParams.rightMargin = -250;
layoutParams.bottomMargin = -250;
v.setLayoutParams(layoutParams);
break;
}
_root.invalidate();
return true;
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linear_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="AddButton"
android:text="Button" />
<RelativeLayout
android:id="#+id/relative_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/btnAdd" >
</RelativeLayout>
</RelativeLayout>
I was able to tackle this by using these conditions:
if ((v.getY() < lay.getY())) {
v.setX(xVal);
v.setY(yVal);
} else if (v.getX() < lay.getX()) {
v.setX(xVal);
v.setY(yVal);
} else if (v.getX() + v.getWidth() > lay.getX() + lay.getWidth()) {
v.setX(xVal);
v.setY(yVal);
} else if (v.getY() + v.getHeight() > lay.getY() + lay.getHeight()) {
v.setX(xVal);
v.setY(yVal);
} else {
for (int i = 0; i <= viewIdList.size() - 1; i++) {
if (v.getId() != viewIdList.get(i).getId()) {
View v3 = viewIdList.get(i);
Rect rect1 = new Rect(v.getLeft(), v.getTop(),
v.getRight(), v.getBottom());
v.getHitRect(rect1);
Rect rect2 = new Rect(v3.getLeft(), v3.getTop(),
v3.getRight(), v3.getBottom());
v3.getHitRect(rect2);
if (Rect.intersects(rect1, rect2)) {
System.out.println("overlap");
v.setX(xVal);
v.setY(yVal);
}
where v is the view (ImageView in my case) and this code is written in MotionEvent.ACTION_UP of onTouchListener.
I created my custom Slide Menu. I used FrameLayout to show my custom slide menu. I have one problem. In a small divice my slide menu is working perfectly ,but in a large device fragment is not working. I can not show fragments components (for example buttons etc.).
This is my code:
<com.android.slidingmenuexample.MainLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/geo"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#drawable/geocell" />
<ListView
android:id="#+id/menu_listview"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#drawable/header"
android:orientation="horizontal" >
<Button
android:id="#+id/button_menu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/menumm"
android:onClick="toggleMenu" />
</LinearLayout>
<FrameLayout
android:id="#+id/activity_main_content_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
</LinearLayout>
public class MainLayout extends LinearLayout {
private static final int SLIDING_DURATION = 500;
private static final int QUERY_INTERVAL = 16;
int mainLayoutWidth;
private View menu;
private View content;
private static int menuRightMargin = 45;
private enum MenuState {
HIDING, HIDDEN, SHOWING, SHOWN,
};
private int contentXOffset;
private MenuState currentMenuState = MenuState.HIDDEN;
private Scroller menuScroller = new Scroller(this.getContext(),
new EaseInInterpolator());
private Runnable menuRunnable = new MenuRunnable();
private Handler menuHandler = new Handler();
int prevX = 0;
boolean isDragging = false;
int lastDiffX = 0;
public MainLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MainLayout(Context context) {
super(context);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
mainLayoutWidth = MeasureSpec.getSize(widthMeasureSpec);
menuRightMargin = mainLayoutWidth * 50 / 100;
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
menu = this.getChildAt(0);
content = this.getChildAt(1);
content.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return MainLayout.this.onContentTouch(v, event);
}
});
menu.setVisibility(View.GONE);
}
#Override
protected void onLayout(boolean changed, int left, int top, int right,
int bottom) {
if (changed) {
LayoutParams contentLayoutParams = (LayoutParams) content
.getLayoutParams();
contentLayoutParams.height = this.getHeight();
contentLayoutParams.width = this.getWidth();
LayoutParams menuLayoutParams = (LayoutParams) menu
.getLayoutParams();
menuLayoutParams.height = this.getHeight();
menuLayoutParams.width = this.getWidth() - menuRightMargin;
}
menu.layout(left, top, right - menuRightMargin, bottom);
content.layout(left + contentXOffset, top, right + contentXOffset,
bottom);
}
public void toggleMenu() {
if (currentMenuState == MenuState.HIDING
|| currentMenuState == MenuState.SHOWING)
return;
switch (currentMenuState) {
case HIDDEN:
currentMenuState = MenuState.SHOWING;
menu.setVisibility(View.VISIBLE);
menuScroller.startScroll(0, 0, menu.getLayoutParams().width, 0,
SLIDING_DURATION);
break;
case SHOWN:
currentMenuState = MenuState.HIDING;
menuScroller.startScroll(contentXOffset, 0, -contentXOffset, 0,
SLIDING_DURATION);
break;
default:
break;
}
menuHandler.postDelayed(menuRunnable, QUERY_INTERVAL);
this.invalidate();
}
protected class MenuRunnable implements Runnable {
#Override
public void run() {
boolean isScrolling = menuScroller.computeScrollOffset();
adjustContentPosition(isScrolling);
}
}
private void adjustContentPosition(boolean isScrolling) {
int scrollerXOffset = menuScroller.getCurrX();
content.offsetLeftAndRight(scrollerXOffset - contentXOffset);
contentXOffset = scrollerXOffset;
this.invalidate();
if (isScrolling)
menuHandler.postDelayed(menuRunnable, QUERY_INTERVAL);
else
this.onMenuSlidingComplete();
}
private void onMenuSlidingComplete() {
switch (currentMenuState) {
case SHOWING:
currentMenuState = MenuState.SHOWN;
break;
case HIDING:
currentMenuState = MenuState.HIDDEN;
menu.setVisibility(View.GONE);
break;
default:
return;
}
}
protected class EaseInInterpolator implements Interpolator {
#Override
public float getInterpolation(float t) {
return (float) Math.pow(t - 1, 5) + 1;
}
}
public boolean isMenuShown() {
return currentMenuState == MenuState.SHOWN;
}
public boolean onContentTouch(View v, MotionEvent event) {
if (currentMenuState == MenuState.HIDING
|| currentMenuState == MenuState.SHOWING)
return false;
int curX = (int) event.getRawX();
int diffX = 0;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
prevX = curX;
return true;
case MotionEvent.ACTION_MOVE:
if (!isDragging) {
isDragging = true;
menu.setVisibility(View.VISIBLE);
}
diffX = curX - prevX;
if (contentXOffset + diffX <= 0) {
diffX = -contentXOffset;
} else if (contentXOffset + diffX > mainLayoutWidth
- menuRightMargin) {
diffX = mainLayoutWidth - menuRightMargin - contentXOffset;
}
content.offsetLeftAndRight(diffX);
contentXOffset += diffX;
this.invalidate();
prevX = curX;
lastDiffX = diffX;
return true;
case MotionEvent.ACTION_UP:
Log.d("MainLayout.java onContentTouch()", "Up lastDiffX "
+ lastDiffX);
if (lastDiffX > 0) {
currentMenuState = MenuState.SHOWING;
menuScroller.startScroll(contentXOffset, 0,
menu.getLayoutParams().width - contentXOffset, 0,
SLIDING_DURATION);
} else if (lastDiffX < 0) {
currentMenuState = MenuState.HIDING;
menuScroller.startScroll(contentXOffset, 0, -contentXOffset, 0,
SLIDING_DURATION);
}
menuHandler.postDelayed(menuRunnable, QUERY_INTERVAL);
this.invalidate();
isDragging = false;
prevX = 0;
lastDiffX = 0;
return true;
default:
break;
}
return false;
}
}
And MainActivity java class
ublic class MainActivity extends FragmentActivity {
MainLayout mLayout;
ProgressDialog dialog;
Button btMenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
mLayout = (MainLayout) this.getLayoutInflater().inflate(
R.layout.activity_main, null);
setContentView(mLayout);
dialog = ProgressDialog.show(this, "Please Wait... ", "Loading... ");
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
btMenu = (Button) findViewById(R.id.button_menu);
btMenu.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Show/hide the menu
toggleMenu(v);
}
});
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
FragmentManager fm = MainActivity.this
.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Layout1 fragment = new Layout1();
ft.add(R.id.activity_main_content_fragment, fragment);
ft.commit();
if (dialog != null) {
dialog.dismiss();
}
}
}, 10000);
}
public void toggleMenu(View v) {
mLayout.toggleMenu();
}
#Override
public void onBackPressed() {
if (mLayout.isMenuShown()) {
mLayout.toggleMenu();
} else {
super.onBackPressed();
}
}
}
I have problem only large screen resolution. In a small and medium screen resolution program working perfect. if i touch layot in a large screen then working perfect but if i click Button tu call toggleMenu function then not working. in my option problem is toggleMenu function ,but i do not know what is a wrong
You need to maintain different folders to support multiple screens in android.
The following is a list of resource directories in an application that provides different layout designs for different screen sizes and different bitmap drawables for medium, high, and extra high density screens.
res/layout/my_layout.xml // layout for normal screen size ("default")
res/layout-small/my_layout.xml // layout for small screen size
res/layout-large/my_layout.xml // layout for large screen size
res/layout-xlarge/my_layout.xml // layout for extra large screen size
res/layout-xlarge-land/my_layout.xml // layout for extra large in landscape orientation
res/drawable-mdpi/my_icon.png // bitmap for medium density
res/drawable-hdpi/my_icon.png // bitmap for high density
res/drawable-xhdpi/my_icon.png // bitmap for extra high density
For more info refer this link