Is there any control over Carousel viewpager item position? - android

I have already implemented Carousel Viewpager ...but I m stuck at one point.
There is 10 image item in ArrayList ...First 3 item (0,1,2 position) are showing and we can scroll horizontally one by one
What I want, When I click on first position i.e, 0 it should go position 1 and when I click on position 2, it should come position 1.
How can I achieve this?enter image description here
Method in mainActivity
private void showDrinkList() {
try {
DisplayMetrics metrics = new DisplayMetrics();
Objects.requireNonNull(getActivity()).getWindowManager().getDefaultDisplay().getMetrics(metrics);
int pageMargin = ((metrics.widthPixels / 3) * 2);
pager.setPageMargin(-pageMargin);
CarouselPagerAdapter adapter = new CarouselPagerAdapter(context,this.getChildFragmentManager(), this.getChildFragmentManager(), pager, drinkLists);
pager.setAdapter(adapter);
pager.addOnPageChangeListener(adapter);
if (drinkLists.size() > 1)
pager.setCurrentItem(1);
pager.setOffscreenPageLimit(3);
pager.setHorizontalScrollBarEnabled(true);
} catch (Exception e) {
e.printStackTrace();
} }
Carousel Adapter -
import android.content.Context;
import android.graphics.Interpolator;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.widget.Toast;
import java.lang.reflect.Field;
import java.util.List;
import ae.frink.android.R;
import ae.frink.android.app.customDialog.RedeemDialog;
import ae.frink.android.model.BeanDrinkImage;
import ae.frink.android.utils.FixedSpeedScroller;
import ae.frink.android.utils.ViewPagerCustomDuration;
public class CarouselPagerAdapter extends FragmentPagerAdapter implements ViewPager.OnPageChangeListener {
public final static float BIG_SCALE = 0.8f;
private final static float SMALL_SCALE = 0.4f;
private final static float DIFF_SCALE = BIG_SCALE - SMALL_SCALE;
private FragmentManager context;
private Context c;
private FragmentManager fragmentManager;
private float scale;
public static ViewPager viewPager;
private List<BeanDrinkImage.DrinkList> drinkLists;
private CarouselPagerAdapter adapter;
//private ItemFragment itemFragment;
public CarouselPagerAdapter(Context c, FragmentManager context, FragmentManager fm, ViewPager viewPager,
List<BeanDrinkImage.DrinkList> drinkLists) {
super(fm);
this.fragmentManager = fm;
this.context = context;
this.c = c;
// this.itemFragment = new ItemFragment(drinkLists);
this.viewPager = viewPager;
this.drinkLists = drinkLists;}
#Override
public Fragment getItem(int position) {
// make the first pager bigger than others
try {
if (position == 0) //BarInformationFrag.FIRST_PAGE)
scale = SMALL_SCALE;
else if(position == 1)
scale = BIG_SCALE;
else if(position == 2)
scale = SMALL_SCALE;
else
scale = SMALL_SCALE;
position = position % drinkLists.size();
} catch (Exception e) {
e.printStackTrace();
}
Log.e("drinkSize", "....----" + drinkLists.size());
// ItemFragment itemFragment = new ItemFragment();
return ItemFragment.newInstance(context, position, scale, drinkLists);
}
#Override
public int getCount() {
// int count = 0;
// try {
// count = BarInformationFrag.count * BarInformationFrag.LOOPS;
// } catch (Exception e) {
// // TODO: handle exception
// e.printStackTrace();
// }
// return count;
return drinkLists.size();
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
try {
if (positionOffset >= 0f && positionOffset <= 1f) {
CarouselLinearLayout cur = getRootView(position);
CarouselLinearLayout next = getRootView(position + 1);
cur.setScaleBoth(BIG_SCALE - DIFF_SCALE * positionOffset);
next.setScaleBoth(SMALL_SCALE + DIFF_SCALE * positionOffset);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
#SuppressWarnings("ConstantConditions")
private CarouselLinearLayout getRootView(int position) {
return (CarouselLinearLayout) fragmentManager.findFragmentByTag(this.getFragmentTag(position))
.getView().findViewById(R.id.root_container);
}
private String getFragmentTag(int position) {
return "android:switcher:" + viewPager.getId() + ":" + position;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
Carousel Linear Layout -
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.widget.LinearLayout;
public class CarouselLinearLayout extends LinearLayout {
private float scale = CarouselPagerAdapter.BIG_SCALE;
// private float scale = .5f;
public CarouselLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CarouselLinearLayout(Context context) {
super(context);
}
public void setScaleBoth(float scale) {
this.scale = scale;
this.invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// The main mechanism to display scale animation, you can customize it as your needs
int w = this.getWidth();
int h = this.getHeight();
canvas.scale(scale, scale, w / 2, h / 2);
}
}
item Fragment -
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import ae.frink.android.R;
import ae.frink.android.app.customDialog.RedeemDialog;
import ae.frink.android.connection.ApiClient;
import ae.frink.android.model.BeanDrinkImage;
import static ae.frink.android.Carousel.CarouselPagerAdapter.viewPager;
public class ItemFragment extends Fragment {
private static final String POSITON = "position";
private static final String SCALE = "scale";
private static final String DRAWABLE_RESOURE = "resource";
private static final String DRINK_LIST = "drinkList";
private List<BeanDrinkImage.DrinkList> dL;
private static final String IMAGE = "image";
public ArrayList<Integer> imageArray;
private Context context;
private List<BeanDrinkImage.DrinkList> drinkLists;
private SharedPreferences sharedPreferences;
private int screenWidth;
private int screenHeight;
/* private int[] imageArray = new int[]{R.drawable.cocktail_lime_gin_fizz_1, R.drawable.cocktail_lime_gin_fizz_1,
R.drawable.cocktail_lime_gin_fizz_1, R.drawable.cocktail_lime_gin_fizz_1, R.drawable.cocktail_lime_gin_fizz_1,
R.drawable.cocktail_lime_gin_fizz_1, R.drawable.cocktail_lime_gin_fizz_1, R.drawable.cocktail_lime_gin_fizz_1,
R.drawable.cocktail_lime_gin_fizz_1, R.drawable.cocktail_lime_gin_fizz_1};
*/
public ItemFragment() {
}
/*
#SuppressLint("ValidFragment")
public ItemFragment(List<BeanDrinkImage.DrinkList> drinkLists) {
this.drinkLists = drinkLists;
}
*/
public static Fragment newInstance(FragmentManager context, int pos, float scale, List<BeanDrinkImage.DrinkList> dL) {
ItemFragment fr = new ItemFragment();
Bundle b = new Bundle();
b.putInt(POSITON, pos);
b.putFloat(SCALE, scale);
b.putParcelableArrayList(DRINK_LIST, (ArrayList) dL);
//drinkLists=dL;
// this.context = context;
// this.dL = dL;
// b.putIntegerArrayList(IMAGE, imageArray);
Log.e("drinkSize", "....+++"+dL.size());
fr.setArguments(b);
return fr;//frFragment.instantiate(context, ItemFragment.class.getName(), b);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWidthAndHeight();
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
}
#SuppressLint("SetTextI18n")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (container == null) {
return null;
}
context = getActivity();
final int postion = this.getArguments().getInt(POSITON);
float scale = this.getArguments().getFloat(SCALE);
this.imageArray = this.getArguments().getIntegerArrayList(IMAGE);
drinkLists = (ArrayList) this.getArguments().getParcelableArrayList(DRINK_LIST);
// TODO 21 sep changes
// LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(screenWidth / 3,
// h/4);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(screenWidth / 2,
screenWidth/2);
LinearLayout linearLayout = (LinearLayout) inflater.inflate(R.layout.fragment_image, container, false);
TextView textView = (TextView) linearLayout.findViewById(R.id.text);
CarouselLinearLayout root = (CarouselLinearLayout) linearLayout.findViewById(R.id.root_container);
ImageView imageView = (ImageView) linearLayout.findViewById(R.id.pagerImg);
ImageView starImage = (ImageView) linearLayout.findViewById(R.id.imgStar);
imageView.setLayoutParams(layoutParams);
String imageUrl = "";
try {
Log.e("drinkSize", "...."+drinkLists.size());
if (drinkLists.size() > 0) {
imageUrl = ApiClient.IMAGE_URL + drinkLists.get(postion).getImage();
Picasso.get().load(imageUrl).into(imageView);
Log.e("drinkName", drinkLists.get(postion).getDrinkName());
textView.setText(drinkLists.get(postion).getDrinkName());
if (drinkLists.get(postion).getIs_recomended() == 1) {
starImage.setVisibility(View.VISIBLE);
} else {
starImage.setVisibility(View.INVISIBLE);
}
}
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (getActivity() != null) {
RedeemDialog redeemDialog = new RedeemDialog(getActivity(), drinkLists, postion);
redeemDialog.setCanceledOnTouchOutside(true);
redeemDialog.show();
// 12-march
/* if (sharedPreferences.getString(CommonVar.IS_SUBSCRIBED, "0").equals("0")) {
Toast.makeText(getContext(), "Please subscribe first", Toast.LENGTH_SHORT).show();
} else {
RedeemDialog redeemDialog = new RedeemDialog(getActivity(), list, postion);
redeemDialog.setCanceledOnTouchOutside(true);
redeemDialog.show();
}*/
}
}
});
root.setScaleBoth(scale);
} catch (Exception e) {
e.printStackTrace();
}
return linearLayout;
}
/**
* Get device screen width and height
*/
private void getWidthAndHeight() {
DisplayMetrics displaymetrics = new DisplayMetrics();
try {
Objects.requireNonNull(getActivity()).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
screenHeight = displaymetrics.heightPixels;
screenWidth = displaymetrics.widthPixels;
} catch (Exception e) {
e.printStackTrace();
}
}
}

if (position == 0) {
scale = SMALL_SCALE;}
else if(position == 1){
scale = BIG_SCALE;
}
else if(position == 2)
{
scale = SMALL_SCALE;
}
else{
scale = SMALL_SCALE;
}

holder.setIsRecyclable(false);

Related

How to add the android view on top of html view but not full screen?

I am creating the app in ionic framework and I am calling the custom plugin which have the video player. Now my problem is Video player is opening in new window rather than current opening window. I want it to open on top of my Html page but not full screen only half screen. the final page will have html page on top of that In right side half page i want my plugin to open.any help how to do this thanks in advance.
this is my plugin
package cordova.plugin.VLCPlugin;
import android.app.Activity;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.mindtree.gladiuscms.R;
import org.videolan.libvlc.EventHandler;
import org.videolan.libvlc.IVideoPlayer;
import org.videolan.libvlc.LibVLC;
import org.videolan.libvlc.Media;
import org.videolan.libvlc.MediaList;
import java.lang.ref.WeakReference;
import cordova.plugin.VLCPlugin.util.SystemUiHider;
import cordova.plugin.VLCPlugin.util.UrlProvider;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*
* #see SystemUiHider
*/
public class FullscreenVlcPlayer extends Activity implements SurfaceHolder.Callback, IVideoPlayer {
private String urlToStream;
// Display Surface
private LinearLayout vlcContainer;
private SurfaceView mSurface;
private SurfaceHolder holder;
// Overlay / Controls
private FrameLayout vlcOverlay;
private ImageView vlcButtonPlayPause;
private Handler handlerOverlay;
private Runnable runnableOverlay;
private Handler handlerSeekbar;
private Runnable runnableSeekbar;
private SeekBar vlcSeekbar;
private TextView vlcDuration;
private TextView overlayTitle;
// media player
private LibVLC libvlc;
private int mVideoWidth;
private int mVideoHeight;
private final static int VideoSizeChanged = -1;
private UrlProvider urlProvider = new UrlProvider();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Retrieve our url
// Bundle b = getIntent().getExtras();
UrlProvider urlProvider = UrlProvider.getInstance();
urlToStream = urlProvider.getUrl();
Log.d("Data url sdfjksdf", urlToStream);
// urlToStream = "rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov";// b.getString("url", null);
// HIDE THE ACTION BAR
// getActionBar().hide();
// SETUP THE UI
try{
getActionBar().hide();
setContentView(R.layout.activity_fullscreen_vlc_player);
}catch(Exception e){
Log.d("TAG", "error");
}
// VLC
vlcContainer = (LinearLayout) findViewById(R.id.vlc_container);
mSurface = (SurfaceView) findViewById(R.id.vlc_surface);
// OVERLAY / CONTROLS
vlcOverlay = (FrameLayout) findViewById(R.id.vlc_overlay);
vlcButtonPlayPause = (ImageView) findViewById(R.id.vlc_button_play_pause);
vlcSeekbar = (SeekBar) findViewById(R.id.vlc_seekbar);
vlcDuration = (TextView) findViewById(R.id.vlc_duration);
overlayTitle = (TextView) findViewById(R.id.vlc_overlay_title);
// overlayTitle.setText("rtsp://172.22.68.96:21212/Stream-2");
// AUTOSTART
playMovie();
}
private void showOverlay() {
vlcOverlay.setVisibility(View.VISIBLE);
}
private void hideOverlay() {
vlcOverlay.setVisibility(View.GONE);
}
private void setupControls() {
getActionBar().hide();
// PLAY PAUSE
vlcButtonPlayPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (libvlc.isPlaying()) {
libvlc.pause();
// vlcButtonPlayPause.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_play_over_video));
} else {
libvlc.play();
// vlcButtonPlayPause.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_pause_over_video));
}
}
});
// SEEKBAR
handlerSeekbar = new Handler();
runnableSeekbar = new Runnable() {
#Override
public void run() {
if (libvlc != null) {
long curTime = libvlc.getTime();
long totalTime = (long) (curTime / libvlc.getPosition());
int minutes = (int) (curTime / (60 * 1000));
int seconds = (int) ((curTime / 1000) % 60);
int endMinutes = (int) (totalTime / (60 * 1000));
int endSeconds = (int) ((totalTime / 1000) % 60);
String duration = String.format("%02d:%02d / %02d:%02d", minutes, seconds, endMinutes, endSeconds);
vlcSeekbar.setProgress((int) (libvlc.getPosition() * 100));
vlcDuration.setText(duration);
}
handlerSeekbar.postDelayed(runnableSeekbar, 1000);
}
};
runnableSeekbar.run();
vlcSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
Log.v("NEW POS", "pos is : " + i);
//if (i != 0)
// libvlc.setPosition(((float) i / 100.0f));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
// OVERLAY
handlerOverlay = new Handler();
runnableOverlay = new Runnable() {
#Override
public void run() {
vlcOverlay.setVisibility(View.GONE);
toggleFullscreen(true);
}
};
final long timeToDisappear = 3000;
handlerOverlay.postDelayed(runnableOverlay, timeToDisappear);
vlcContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
vlcOverlay.setVisibility(View.VISIBLE);
handlerOverlay.removeCallbacks(runnableOverlay);
handlerOverlay.postDelayed(runnableOverlay, timeToDisappear);
}
});
}
public void playMovie() {
if (libvlc != null && libvlc.isPlaying())
return ;
vlcContainer.setVisibility(View.VISIBLE);
holder = mSurface.getHolder();
holder.addCallback(this);
createPlayer(urlToStream);
}
private void toggleFullscreen(boolean fullscreen)
{
WindowManager.LayoutParams attrs = getWindow().getAttributes();
if (fullscreen)
{
attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
vlcContainer.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
else
{
attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
}
getWindow().setAttributes(attrs);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setSize(mVideoWidth, mVideoHeight);
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
//releasePlayer();
}
#Override
protected void onDestroy() {
super.onDestroy();
releasePlayer();
}
/**
* **********
* Surface
* ***********
*/
public void surfaceCreated(SurfaceHolder holder) {
}
public void surfaceChanged(SurfaceHolder surfaceholder, int format,
int width, int height) {
if (libvlc != null)
libvlc.attachSurface(surfaceholder.getSurface(), this);
}
public void surfaceDestroyed(SurfaceHolder surfaceholder) {
}
private void setSize(int width, int height) {
mVideoWidth = width;
mVideoHeight = height;
if (mVideoWidth * mVideoHeight <= 1)
return;
// get screen size
int w = getWindow().getDecorView().getWidth();
int h = getWindow().getDecorView().getHeight();
// getWindow().getDecorView() doesn't always take orientation into
// account, we have to correct the values
boolean isPortrait = getResources().getConfiguration().orientation `**enter code here**`== Configuration.ORIENTATION_PORTRAIT;
if (w > h && isPortrait || w < h && !isPortrait) {
int i = w;
w = h;
h = i;
}
float videoAR = (float) mVideoWidth / (float) mVideoHeight;
float screenAR = (float) w / (float) h;
if (screenAR < videoAR)
h = (int) (w / videoAR);
else
w = (int) (h * videoAR);
// force surface buffer size
if (holder != null)
holder.setFixedSize(mVideoWidth, mVideoHeight);
// set display size
ViewGroup.LayoutParams lp = mSurface.getLayoutParams();
lp.width = w;
lp.height = h;
mSurface.setLayoutParams(lp);
mSurface.invalidate();
}
#Override
public void setSurfaceSize(int width, int height, int visible_width,
int visible_height, int sar_num, int sar_den) {
Message msg = Message.obtain(mHandler, VideoSizeChanged, width, height);
msg.sendToTarget();
}
/**
* **********
* Player
* ***********
*/
private void createPlayer(String media) {
releasePlayer();
setupControls();
try {
if (media.length() > 0) {
Toast toast = Toast.makeText(this, media, Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0,
0);
toast.show();
}
// Create a new media player
libvlc = LibVLC.getInstance();
libvlc.setHardwareAcceleration(LibVLC.HW_ACCELERATION_FULL);
libvlc.eventVideoPlayerActivityCreated(true);
libvlc.setSubtitlesEncoding("");
libvlc.setAout(LibVLC.AOUT_OPENSLES);
libvlc.setTimeStretching(true);
libvlc.setChroma("RV32");
libvlc.setVerboseMode(true);
LibVLC.restart(this);
EventHandler.getInstance().addHandler(mHandler);
holder.setFormat(PixelFormat.RGBX_8888);
holder.setKeepScreenOn(true);
MediaList list = libvlc.getMediaList();
list.clear();
list.add(new Media(libvlc, LibVLC.PathToURI(media)), false);
libvlc.playIndex(0);
} catch (Exception e) {
Toast.makeText(this, "Could not create Vlc Player", Toast.LENGTH_LONG).show();
}
}
private void releasePlayer() {
if (handlerSeekbar != null && runnableSeekbar != null)
handlerSeekbar.removeCallbacks(runnableSeekbar);
EventHandler.getInstance().removeHandler(mHandler);
if (libvlc == null)
return;
libvlc.stop();
libvlc.detachSurface();
holder = null;
libvlc.closeAout();
mVideoWidth = 0;
mVideoHeight = 0;
}
/**
* **********
* Events
* ***********
*/
private Handler mHandler = new MyHandler(this);
private static class MyHandler extends Handler {
private WeakReference<FullscreenVlcPlayer> mOwner;
public MyHandler(FullscreenVlcPlayer owner) {
mOwner = new WeakReference<FullscreenVlcPlayer>(owner);
}
#Override
public void handleMessage(Message msg) {
FullscreenVlcPlayer player = mOwner.get();
// Player events
if (msg.what == VideoSizeChanged) {
player.setSize(msg.arg1, msg.arg2);
return;
}
// Libvlc events
Bundle b = msg.getData();
switch (b.getInt("event")) {
case EventHandler.MediaPlayerEndReached:
player.releasePlayer();
break;
case EventHandler.MediaPlayerPlaying:
case EventHandler.MediaPlayerPaused:
case EventHandler.MediaPlayerStopped:
default:
break;
}
}
}
}
//it use some helper class and
xml file attached to this
cordova plugin
package cordova.plugin.VLCPlugin;
import android.app.Application;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Rect;
import android.widget.FrameLayout;
import com.mindtree.gladiuscms.R;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
import cordova.plugin.VLCPlugin.util.UrlProvider;
public class VLCPlugin extends CordovaPlugin {
UrlProvider urlProvider = new UrlProvider();
#Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
FrameLayout layout = (FrameLayout) webView.getView().getParent();
}
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if(action.equals("play")) {
String url = args.getString(0);
UrlProvider urlProvide = UrlProvider.getInstance();
urlProvide.setUrl(url);
resources.getIdentifier("R.layout.activity_fullscreen_vlc_player", "layout", package_name);
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
Application app = cordova.getActivity().getApplication();
Intent intent = new Intent(app, FullscreenVlcPlayer.class);
cordova.getActivity().startActivity(intent);
}
return false;
}
}
now i am cslling this plugin from my controller
window.vlcPlugin.onMediaLoad("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4");}
an my html code is
<div ng-drag="true" ng-drag-data="video" ng-drag-success="onDragComplete()"></div>
i want to see video in this div
<div class="video_player_screen" ng-drop="tru >

I want to set images into into gridview from SD card?

Below is my AppConstant.java
package com.domore.gridviewtutorial.helper;
import java.util.Arrays;
import java.util.List;
/**
* Created by MY WORLD on 11/28/2015.
*/
public class AppContant {
// Number of columns of Grid View
public static final int NUM_OF_COLUMNS = 3;
// Gridview image padding
public static final int GRID_PADDING = 8; // in dp
// SD card image directory
public static final String PHOTO_ALBUM = "MyPhotos";
// supported file formats
public static final List<String> FILE_EXTN = Arrays.asList("jpg", "jpeg",
"png");
}
in this class i set the file extension which i load in my app
Here, is my utils class
package com.domore.gridviewtutorial.helper;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Point;
import android.view.Display;
import android.view.WindowManager;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.Locale;
/**
* Created by MY WORLD on 11/28/2015.
*/
public class Utils {
private Context context;
public Utils(Context context){
this.context=context;
}
public ArrayList<String> getFilePaths(){
ArrayList<String> filePaths=new ArrayList<String>();
File directory=new File(android.os.Environment.getExternalStorageDirectory()+File.separator+AppContant.PHOTO_ALBUM);
if(directory.isDirectory()){
File[] listFiles=directory.listFiles();
if(listFiles.length > 0 ){
for(int i=0;i<listFiles.length;i++){
String filePath=listFiles[i].getAbsolutePath();
if(IsSupportedFile(filePath)){
filePaths.add(filePath);
}
}
}
else{
Toast.makeText(
context,
AppContant.PHOTO_ALBUM
+ " is empty. Please load some images in it !",
Toast.LENGTH_LONG).show();
}
}
else{
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Error!");
alert.setMessage(AppContant.PHOTO_ALBUM
+ " directory path is not valid! Please set the image directory name AppConstant.java class");
alert.setPositiveButton("OK", null);
alert.show();
}
return filePaths;
}
private boolean IsSupportedFile(String filePath) {
String ext = filePath.substring((filePath.lastIndexOf(".") + 1),
filePath.length());
if (AppContant.FILE_EXTN
.contains(ext.toLowerCase(Locale.getDefault())))
return true;
else
return false;
}
public int getScreenWidth() {
int columnWidth;
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
final Point point = new Point();
try {
display.getSize(point);
} catch (java.lang.NoSuchMethodError ignore) { // Older device
point.x = display.getWidth();
point.y = display.getHeight();
}
columnWidth = point.x;
return columnWidth;
}
}
Here is my grid_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/grid_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="auto_fit"
android:gravity="center"
android:stretchMode="columnWidth"
android:background="#000000">
</GridView>
i have Adapter class to load images
package com.domore.gridviewtutorial.adapter;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.GridView;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import android.view.View.OnClickListener;
/**
* Created by MY WORLD on 11/28/2015.
*/
public class GridViewImageAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<String> _filePaths=new ArrayList<String>();
private int imageWidth;
public GridViewImageAdapter(Activity activity,ArrayList<String> _filePaths,int imageWidth){
this.activity=activity;
this._filePaths=_filePaths;
this.imageWidth=imageWidth;
}
#Override
public int getCount() {
return this._filePaths.size();
}
#Override
public Object getItem(int position) {
return this._filePaths.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if(convertView==null){
imageView=new ImageView(this.activity);
}
else{
imageView=(ImageView)convertView;
}
Bitmap image=decodeFile(this._filePaths.get(position),imageWidth,imageWidth);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth,
imageWidth));
imageView.setImageBitmap(image);
// image view click listener
imageView.setOnClickListener(new OnImageClickListener(position));
return imageView;
}
class OnImageClickListener implements OnClickListener {
int _postion;
// constructor
public OnImageClickListener(int position) {
this._postion = position;
}
#Override
public void onClick(View v) {
// on selecting grid view image
// launch full screen activity
// Intent i = new Intent(activity, FullScreenViewActivity.class);
// i.putExtra("position", _postion);
// activity.startActivity(i);
}
}
/*
* Resizing image size
*/
public static Bitmap decodeFile(String filePath, int WIDTH, int HIGHT) {
try {
File f = new File(filePath);
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
final int REQUIRED_WIDTH = WIDTH;
final int REQUIRED_HIGHT = HIGHT;
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_WIDTH
&& o.outHeight / scale / 2 >= REQUIRED_HIGHT)
scale *= 2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
Here is my MainActivity.java
package com.domore.gridviewtutorial;
import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.GridLayoutAnimationController;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import com.domore.gridviewtutorial.adapter.GridViewImageAdapter;
import com.domore.gridviewtutorial.helper.AppContant;
import com.domore.gridviewtutorial.helper.Utils;
import java.util.ArrayList;
public class AndroidGridLayoutActivity extends AppCompatActivity {
private Utils utils;
private ArrayList<String> imagePaths = new ArrayList<String>();
private GridViewImageAdapter adapter;
private GridView gridView;
private int columnWidth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_layout);
GridView gridView=(GridView)findViewById(R.id.grid_view);
utils=new Utils(this);
InitilizeGridLayout();
imagePaths=utils.getFilePaths();
adapter=new GridViewImageAdapter(AndroidGridLayoutActivity.this,imagePaths,columnWidth);
gridView.setAdapter(adapter);
}
private void InitilizeGridLayout() {
Resources r = getResources();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
AppContant.GRID_PADDING, r.getDisplayMetrics());
columnWidth = (int) ((utils.getScreenWidth() - ((AppContant.NUM_OF_COLUMNS + 1) * padding)) / AppContant.NUM_OF_COLUMNS);
gridView.setNumColumns(AppContant.NUM_OF_COLUMNS);
gridView.setColumnWidth(columnWidth);
gridView.setStretchMode(GridView.NO_STRETCH);
gridView.setPadding((int) padding, (int) padding, (int) padding,
(int) padding);
gridView.setHorizontalSpacing((int) padding);
gridView.setVerticalSpacing((int) padding);
}
}
I got error in mainActivity.java
here is my error
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.GridView.setNumColumns(int)' on a null object reference
at com.domore.gridviewtutorial.AndroidGridLayoutActivity.InitilizeGridLayout(AndroidGridLayoutActivity.java:46)
at com.domore.gridviewtutorial.AndroidGridLayoutActivity.onCreate(AndroidGridLayoutActivity.java:34)
can anyone who help me to solve out this error i cannot able to understand.
Your gridView variable is null because you are recreating the a new variable gridView in your onCreate() method and your's activity's instance gridView variable is never get Initialized.
public class AndroidGridLayoutActivity extends AppCompatActivity {
private Utils utils;
private ArrayList<String> imagePaths = new ArrayList<String>();
private GridViewImageAdapter adapter;
private GridView gridView;
private int columnWidth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_layout);
// initiated the gridView variable
gridView=(GridView)findViewById(R.id.grid_view);
utils=new Utils(this);
InitilizeGridLayout();
imagePaths=utils.getFilePaths();
adapter=new GridViewImageAdapter(AndroidGridLayoutActivity.this,imagePaths,columnWidth);
gridView.setAdapter(adapter);
}
private void InitilizeGridLayout() {
Resources r = getResources();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
AppContant.GRID_PADDING, r.getDisplayMetrics());
columnWidth = (int) ((utils.getScreenWidth() - ((AppContant.NUM_OF_COLUMNS + 1) * padding)) / AppContant.NUM_OF_COLUMNS);
gridView.setNumColumns(AppContant.NUM_OF_COLUMNS);
gridView.setColumnWidth(columnWidth);
gridView.setStretchMode(GridView.NO_STRETCH);
gridView.setPadding((int) padding, (int) padding, (int) padding,
(int) padding);
gridView.setHorizontalSpacing((int) padding);
gridView.setVerticalSpacing((int) padding);
}
}

ParallaxViewPager Right to Left

I am working a project on ParallaxViewPager. I have 3 pages. Everything working normal and the background is parallax as supposed to. But when I add parallaxViewPager.setCurrentItem(2); the background does not appear and it gets default android background. Here is the full code:
MainActivity:
package com.example.myapplication3.app;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.RelativeLayout;
import com.andraskindler.parallaxviewpager.ParallaxViewPager;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ParallaxViewPager parallaxViewPager = ((ParallaxViewPager) findViewById(R.id.parallaxviewpager));
parallaxViewPager.setOverlapPercentage(0.25f);
parallaxViewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
parallaxViewPager.setCurrentItem(2);
}
}
PagerAdapter:
package com.example.myapplication3.app;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;
public class MyPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPagerAdapter(FragmentManager fm) {
super(fm);
this.fragments = new ArrayList<Fragment>();
fragments.add(new view1());
fragments.add(new view2());
fragments.add(new view3());
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
}
View 1,2,3:
package com.example.myapplication3.app;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class view1 extends Fragment { //view2, view3 on the others
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.view1, container, false); //same here view 2,3
return rootView;
}
}
and the layouts are:
MainActivitys' layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:ignore="MergeRootFrame" >
<com.andraskindler.parallaxviewpager.ParallaxViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/parallaxviewpager"
android:layout_width="match_parent"
android:background="#drawable/sanfran"
android:layout_height="match_parent"/>
</RelativeLayout>
View 1,2,3' layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
Thanks in advance for your time and help.
I had the same problem with this component. It something like a conflict between the canvas and the destination rect so anything is drawn where it should be done.
I made a fork of the original source repository to update it. When setCurrentItem is invoked I check the position and store an adjust value that I use later in the onDraw method.
You can check it at https://github.com/yuraksisa/parallaxviewpager
Here is a modification of the ParallaxViewPager:
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.*;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
#SuppressLint("NewApi")
public class ParallaxViewPager extends ViewPager {
public static final int FIT_WIDTH = 0;
public static final int FIT_HEIGHT = 1;
public static final float OVERLAP_FULL = 1f;
public static final float OVERLAP_HALF = 0.5f;
public static final float OVERLAP_QUARTER = 0.25f;
public Bitmap bitmap;
private Rect source, destination;
private int scaleType;
private Paint paint;
private OnPageChangeListener secondOnPageChangeListener;
public ParallaxViewPager(Context context) {
super(context);
init();
}
public ParallaxViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
source = new Rect();
destination = new Rect();
scaleType = FIT_HEIGHT;
setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
if (bitmap != null) {
if (position == 0) {
source.left = (int) ((getWidth() / 8) * positionOffset);
source.right = getWidth() + source.left;
destination.left = (int) ((getWidth() * positionOffset) - getWidth());
destination.right = (int) (0 + (getWidth() * positionOffset));
} else {
source.left = (int) ((getWidth() / 8) - (getWidth() / 8)
* positionOffset);
source.right = getWidth() + source.left;
destination.left = (int) ((0 - getWidth()
* positionOffset));
destination.right = (int) (getWidth() - (getWidth() * positionOffset));
}
postInvalidate();
}
if (secondOnPageChangeListener != null) {
secondOnPageChangeListener.onPageScrolled(position,
positionOffset, positionOffsetPixels);
}
}
#Override
public void onPageSelected(int position) {
if (secondOnPageChangeListener != null) {
secondOnPageChangeListener.onPageSelected(position);
}
}
#Override
public void onPageScrollStateChanged(int state) {
if (secondOnPageChangeListener != null) {
secondOnPageChangeListener.onPageScrollStateChanged(state);
}
}
});
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
destination.top = 0;
destination.bottom = h;
if (getAdapter() != null && bitmap != null)
calculateParallaxParameters();
}
private void calculateParallaxParameters() {
if (bitmap.getWidth() < getWidth()
&& bitmap.getWidth() < bitmap.getHeight()
&& scaleType == FIT_HEIGHT) {
Log.w(ParallaxViewPager.class.getName(),
"Invalid bitmap bounds for the current device, parallax effect will not work.");
}
source.top = 0;
source.bottom = bitmap.getHeight();
}
/**
* Sets the background from a resource file.
*
* #param resid
*/
#Override
public void setBackgroundResource(int resid) {
bitmap = BitmapFactory.decodeResource(getResources(), resid);
}
/**
* Sets the background from a Drawable.
*
* #param background
*/
#Override
public void setBackground(Drawable background) {
bitmap = ((BitmapDrawable) background).getBitmap();
}
/**
* Deprecated. Sets the background from a Drawable.
*
* #param background
*/
#Override
public void setBackgroundDrawable(Drawable background) {
bitmap = ((BitmapDrawable) background).getBitmap();
}
/**
* Sets the background from a bitmap.
*
* #param bitmap
* #return The ParallaxViewPager object itself.
*/
public ParallaxViewPager setBackground(Bitmap bitmap) {
this.bitmap = bitmap;
return this;
}
public ParallaxViewPager setScaleType(final int scaleType) {
if (scaleType != FIT_WIDTH && scaleType != FIT_HEIGHT)
throw new IllegalArgumentException(
"Illegal argument: scaleType must be FIT_WIDTH or FIT_HEIGHT");
this.scaleType = scaleType;
return this;
}
/**
* Sets the amount of overlapping with the setOverlapPercentage(final float
* percentage) method. This is a number between 0 and 1, the smaller it is,
* the slower is the background scrolling.
*
* #param percentage
* #return The ParallaxViewPager object itself.
*/
public ParallaxViewPager setOverlapPercentage(final float percentage) {
if (percentage <= 0 || percentage >= 1)
throw new IllegalArgumentException(
"Illegal argument: percentage must be between 0 and 1");
return this;
}
/**
* Recalculates the parameters of the parallax effect, useful after changes
* in runtime.
*
* #return The ParallaxViewPager object itself.
*/
public ParallaxViewPager invalidateParallaxParameters() {
calculateParallaxParameters();
return this;
}
#Override
protected void onDraw(Canvas canvas) {
if (bitmap != null) {
canvas.drawBitmap(bitmap, source, destination, paint);
}
}
public void addOnPageChangeListener(OnPageChangeListener listener) {
secondOnPageChangeListener = listener;
}
}
And here is how to use:
viewPager = (ParallaxViewPager)findViewById(R.id.lock_viewpager);
viewPager.setBackgroundDrawable(new BitmapDrawable());
viewPager.setAdapter(new MyViewPagerAdapter());
viewPager.addOnPageChangeListener(this);
viewPager.setCurrentItem(mList.size());

Drag and Drop listview with images and text in android

I want to implement drag and drop of list-items in my application. I followed this, it works well for lists containing text only. I integrated lazy-list with images along with drag and drop. But, while I drag the item, the dragged item goes to actual position. The item below the dragged item gets removed from the list. After I take my fingers off, dragged item doesn't move to the place I wish. What is wrong with this code?
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.listviewdragginganimation.DynamicListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"/>
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Clear Cache"/>
</LinearLayout>
DynamicListView.Java:
package com.listviewdragginganimation;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.TypeEvaluator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class DynamicListView extends ListView {
private final int SMOOTH_SCROLL_AMOUNT_AT_EDGE = 15;
private final int MOVE_DURATION = 150;
private final int LINE_THICKNESS = 15;
public ArrayList<String> mCheeseList;
private int mLastEventY = -1;
private int mDownY = -1;
private int mDownX = -1;
private int mTotalOffset = 0;
private boolean mCellIsMobile = false;
private boolean mIsMobileScrolling = false;
private int mSmoothScrollAmountAtEdge = 0;
private final int INVALID_ID = -1;
private long mAboveItemId = INVALID_ID;
private long mMobileItemId = INVALID_ID;
private long mBelowItemId = INVALID_ID;
private BitmapDrawable mHoverCell;
private Rect mHoverCellCurrentBounds;
private Rect mHoverCellOriginalBounds;
private final int INVALID_POINTER_ID = -1;
private int mActivePointerId = INVALID_POINTER_ID;
private boolean mIsWaitingForScrollFinish = false;
private int mScrollState = OnScrollListener.SCROLL_STATE_IDLE;
public DynamicListView(Context context) {
super(context);
init(context);
}
public DynamicListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
public DynamicListView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public void init(Context context) {
setOnItemLongClickListener(mOnItemLongClickListener);
setOnScrollListener(mScrollListener);
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
mSmoothScrollAmountAtEdge = (int) (SMOOTH_SCROLL_AMOUNT_AT_EDGE / metrics.density);
}
private AdapterView.OnItemLongClickListener mOnItemLongClickListener = new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos,
long id) {
mTotalOffset = 0;
int position = pointToPosition(mDownX, mDownY);
int itemNum = position - getFirstVisiblePosition();
View selectedView = getChildAt(itemNum);
mMobileItemId = getAdapter().getItemId(position);
mHoverCell = getAndAddHoverView(selectedView);
selectedView.setVisibility(INVISIBLE);
mCellIsMobile = true;
updateNeighborViewsForID(mMobileItemId);
return true;
}
};
private BitmapDrawable getAndAddHoverView(View v) {
int w = v.getWidth();
int h = v.getHeight();
int top = v.getTop();
int left = v.getLeft();
Bitmap b = getBitmapWithBorder(v);
BitmapDrawable drawable = new BitmapDrawable(getResources(), b);
mHoverCellOriginalBounds = new Rect(left, top, left + w, top + h);
mHoverCellCurrentBounds = new Rect(mHoverCellOriginalBounds);
drawable.setBounds(mHoverCellCurrentBounds);
return drawable;
}
/** Draws a black border over the screenshot of the view passed in. */
private Bitmap getBitmapWithBorder(View v) {
Bitmap bitmap = getBitmapFromView(v);
Canvas can = new Canvas(bitmap);
Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(LINE_THICKNESS);
paint.setColor(Color.BLACK);
can.drawBitmap(bitmap, 0, 0, null);
can.drawRect(rect, paint);
return bitmap;
}
/** Returns a bitmap showing a screenshot of the view passed in. */
private Bitmap getBitmapFromView(View v) {
Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
v.draw(canvas);
return bitmap;
}
private void updateNeighborViewsForID(long itemID) {
int position = getPositionForID(itemID);
LazyAdapter adapter = ((LazyAdapter) getAdapter());
mAboveItemId = adapter.getItemId(position - 1);
mBelowItemId = adapter.getItemId(position + 1);
}
/** Retrieves the view in the list corresponding to itemID */
public View getViewForID(long itemID) {
int firstVisiblePosition = getFirstVisiblePosition();
LazyAdapter adapter = ((LazyAdapter) getAdapter());
for (int i = 0; i < getChildCount(); i++) {
View v = getChildAt(i);
int position = firstVisiblePosition + i;
long id = adapter.getItemId(position);
if (id == itemID) {
return v;
}
}
return null;
}
/** Retrieves the position in the list corresponding to itemID */
public int getPositionForID(long itemID) {
View v = getViewForID(itemID);
if (v == null) {
return -1;
} else {
return getPositionForView(v);
}
}
#Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
if (mHoverCell != null) {
mHoverCell.draw(canvas);
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
mDownX = (int) event.getX();
mDownY = (int) event.getY();
mActivePointerId = event.getPointerId(0);
break;
case MotionEvent.ACTION_MOVE:
if (mActivePointerId == INVALID_POINTER_ID) {
break;
}
int pointerIndex = event.findPointerIndex(mActivePointerId);
mLastEventY = (int) event.getY(pointerIndex);
int deltaY = mLastEventY - mDownY;
if (mCellIsMobile) {
mHoverCellCurrentBounds.offsetTo(mHoverCellOriginalBounds.left,
mHoverCellOriginalBounds.top + deltaY + mTotalOffset);
mHoverCell.setBounds(mHoverCellCurrentBounds);
invalidate();
// Log.v("handle switch 1","1");
handleCellSwitch();
// Log.v("handle switch 2","2");
mIsMobileScrolling = false;
handleMobileCellScroll();
return false;
}
break;
case MotionEvent.ACTION_UP:
touchEventsEnded();
break;
case MotionEvent.ACTION_CANCEL:
touchEventsCancelled();
break;
case MotionEvent.ACTION_POINTER_UP:
pointerIndex = (event.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
final int pointerId = event.getPointerId(pointerIndex);
if (pointerId == mActivePointerId) {
touchEventsEnded();
}
break;
default:
break;
}
return super.onTouchEvent(event);
}
private void handleCellSwitch() {
final int deltaY = mLastEventY - mDownY;
int deltaYTotal = mHoverCellOriginalBounds.top + mTotalOffset + deltaY;
View belowView = getViewForID(mBelowItemId);
View mobileView = getViewForID(mMobileItemId);
View aboveView = getViewForID(mAboveItemId);
boolean isBelow = (belowView != null)
&& (deltaYTotal > belowView.getTop());
boolean isAbove = (aboveView != null)
&& (deltaYTotal < aboveView.getTop());
if (isBelow || isAbove) {
final long switchItemID = isBelow ? mBelowItemId : mAboveItemId;
View switchView = isBelow ? belowView : aboveView;
final int originalItem = getPositionForView(mobileView);
if (switchView == null) {
updateNeighborViewsForID(mMobileItemId);
return;
}
Log.v("swapElements switch 1", "1");
Log.v("swapElements originalItem 1", originalItem + "");
Log.v("swapElements switchView 1", "" + switchView);
setCheeseList(MainActivity.mCheeseList);
Log.v("mCheeseList item", mCheeseList.get(originalItem));
swapElements(mCheeseList, originalItem,
getPositionForView(switchView));
Log.v("swapElements switch 2", "2");
// ((BaseAdapter) getAdapter()).notifyDataSetChanged();
MainActivity.adapter.notifyDataSetChanged();
mDownY = mLastEventY;
final int switchViewStartTop = switchView.getTop();
mobileView.setVisibility(View.VISIBLE);
switchView.setVisibility(View.INVISIBLE);
updateNeighborViewsForID(mMobileItemId);
final ViewTreeObserver observer = getViewTreeObserver();
observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
observer.removeOnPreDrawListener(this);
View switchView = getViewForID(switchItemID);
mTotalOffset += deltaY;
int switchViewNewTop = switchView.getTop();
int delta = switchViewStartTop - switchViewNewTop;
switchView.setTranslationY(delta);
ObjectAnimator animator = ObjectAnimator.ofFloat(
switchView, View.TRANSLATION_Y, 0);
animator.setDuration(MOVE_DURATION);
animator.start();
return true;
}
});
}
}
private void swapElements(ArrayList<String> arrayList, int indexOne,
int indexTwo) {
Log.v("index one", indexOne + "");
Log.v("index two", indexTwo + "");
Log.v("temp", arrayList.get(indexOne));
String temp = arrayList.get(indexOne);
arrayList.set(indexOne, arrayList.get(indexTwo));
arrayList.set(indexTwo, temp);
}
/**
* Resets all the appropriate fields to a default state while also animating
* the hover cell back to its correct location.
*/
private void touchEventsEnded() {
final View mobileView = getViewForID(mMobileItemId);
if (mCellIsMobile || mIsWaitingForScrollFinish) {
mCellIsMobile = false;
mIsWaitingForScrollFinish = false;
mIsMobileScrolling = false;
mActivePointerId = INVALID_POINTER_ID;
// If the autoscroller has not completed scrolling, we need to wait
// for it to
// finish in order to determine the final location of where the
// hover cell
// should be animated to.
if (mScrollState != OnScrollListener.SCROLL_STATE_IDLE) {
mIsWaitingForScrollFinish = true;
return;
}
mHoverCellCurrentBounds.offsetTo(mHoverCellOriginalBounds.left,
mobileView.getTop());
ObjectAnimator hoverViewAnimator = ObjectAnimator.ofObject(
mHoverCell, "bounds", sBoundEvaluator,
mHoverCellCurrentBounds);
hoverViewAnimator
.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(
ValueAnimator valueAnimator) {
invalidate();
}
});
hoverViewAnimator.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationStart(Animator animation) {
setEnabled(false);
}
#Override
public void onAnimationEnd(Animator animation) {
mAboveItemId = INVALID_ID;
mMobileItemId = INVALID_ID;
mBelowItemId = INVALID_ID;
mobileView.setVisibility(VISIBLE);
mHoverCell = null;
setEnabled(true);
invalidate();
}
});
hoverViewAnimator.start();
} else {
touchEventsCancelled();
}
}
/**
* Resets all the appropriate fields to a default state.
*/
private void touchEventsCancelled() {
View mobileView = getViewForID(mMobileItemId);
if (mCellIsMobile) {
mAboveItemId = INVALID_ID;
mMobileItemId = INVALID_ID;
mBelowItemId = INVALID_ID;
mobileView.setVisibility(VISIBLE);
mHoverCell = null;
invalidate();
}
mCellIsMobile = false;
mIsMobileScrolling = false;
mActivePointerId = INVALID_POINTER_ID;
}
/**
* This TypeEvaluator is used to animate the BitmapDrawable back to its
* final location when the user lifts his finger by modifying the
* BitmapDrawable's bounds.
*/
private final static TypeEvaluator<Rect> sBoundEvaluator = new TypeEvaluator<Rect>() {
public Rect evaluate(float fraction, Rect startValue, Rect endValue) {
return new Rect(interpolate(startValue.left, endValue.left,
fraction), interpolate(startValue.top, endValue.top,
fraction), interpolate(startValue.right, endValue.right,
fraction), interpolate(startValue.bottom, endValue.bottom,
fraction));
}
public int interpolate(int start, int end, float fraction) {
return (int) (start + fraction * (end - start));
}
};
private void handleMobileCellScroll() {
mIsMobileScrolling = handleMobileCellScroll(mHoverCellCurrentBounds);
}
public boolean handleMobileCellScroll(Rect r) {
int offset = computeVerticalScrollOffset();
int height = getHeight();
int extent = computeVerticalScrollExtent();
int range = computeVerticalScrollRange();
int hoverViewTop = r.top;
int hoverHeight = r.height();
if (hoverViewTop <= 0 && offset > 0) {
smoothScrollBy(-mSmoothScrollAmountAtEdge, 0);
return true;
}
if (hoverViewTop + hoverHeight >= height && (offset + extent) < range) {
smoothScrollBy(mSmoothScrollAmountAtEdge, 0);
return true;
}
return false;
}
public void setCheeseList(ArrayList<String> cheeseList) {
mCheeseList = cheeseList;
}
private AbsListView.OnScrollListener mScrollListener = new AbsListView.OnScrollListener() {
private int mPreviousFirstVisibleItem = -1;
private int mPreviousVisibleItemCount = -1;
private int mCurrentFirstVisibleItem;
private int mCurrentVisibleItemCount;
private int mCurrentScrollState;
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
mCurrentFirstVisibleItem = firstVisibleItem;
mCurrentVisibleItemCount = visibleItemCount;
mPreviousFirstVisibleItem = (mPreviousFirstVisibleItem == -1) ? mCurrentFirstVisibleItem
: mPreviousFirstVisibleItem;
mPreviousVisibleItemCount = (mPreviousVisibleItemCount == -1) ? mCurrentVisibleItemCount
: mPreviousVisibleItemCount;
checkAndHandleFirstVisibleCellChange();
checkAndHandleLastVisibleCellChange();
mPreviousFirstVisibleItem = mCurrentFirstVisibleItem;
mPreviousVisibleItemCount = mCurrentVisibleItemCount;
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
mCurrentScrollState = scrollState;
mScrollState = scrollState;
isScrollCompleted();
}
private void isScrollCompleted() {
if (mCurrentVisibleItemCount > 0
&& mCurrentScrollState == SCROLL_STATE_IDLE) {
if (mCellIsMobile && mIsMobileScrolling) {
handleMobileCellScroll();
} else if (mIsWaitingForScrollFinish) {
touchEventsEnded();
}
}
}
/**
* Determines if the listview scrolled up enough to reveal a new cell at
* the top of the list. If so, then the appropriate parameters are
* updated.
*/
public void checkAndHandleFirstVisibleCellChange() {
if (mCurrentFirstVisibleItem != mPreviousFirstVisibleItem) {
if (mCellIsMobile && mMobileItemId != INVALID_ID) {
updateNeighborViewsForID(mMobileItemId);
handleCellSwitch();
}
}
}
/**
* Determines if the listview scrolled down enough to reveal a new cell
* at the bottom of the list. If so, then the appropriate parameters are
* updated.
*/
public void checkAndHandleLastVisibleCellChange() {
int currentLastVisibleItem = mCurrentFirstVisibleItem
+ mCurrentVisibleItemCount;
int previousLastVisibleItem = mPreviousFirstVisibleItem
+ mPreviousVisibleItemCount;
if (currentLastVisibleItem != previousLastVisibleItem) {
if (mCellIsMobile && mMobileItemId != INVALID_ID) {
updateNeighborViewsForID(mMobileItemId);
handleCellSwitch();
}
}
}
};
}
LazyAdapter.java:
package com.listviewdragginganimation;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<String> data=new ArrayList<String>();
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(MainActivity a, ArrayList<String> mCheeseList) {
// TODO Auto-generated constructor stub
activity = a;
data=mCheeseList;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.item, null);
TextView text=(TextView)vi.findViewById(R.id.text);;
ImageView image=(ImageView)vi.findViewById(R.id.image);
text.setText("item "+position);
imageLoader.DisplayImage(data.get(position), image);
return vi;
}
}
MainActivity.java:
package com.listviewdragginganimation;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends Activity {
ListView list;
static LazyAdapter adapter;
static ArrayList<String>mCheeseList = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
for (int i = 0; i < mStrings.length; ++i) {
mCheeseList.add(mStrings[i]);
}
list=(ListView)findViewById(R.id.list);
adapter=new LazyAdapter(this, mCheeseList);
list.setAdapter(adapter);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(listener);
}
#Override
public void onDestroy()
{
list.setAdapter(null);
super.onDestroy();
}
public OnClickListener listener=new OnClickListener(){
#Override
public void onClick(View arg0) {
adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}
};
private String[] mStrings={
"http://a3.twimg.com/profile_images/670625317/aam-logo-v3-twitter.png",
"http://a3.twimg.com/profile_images/740897825/AndroidCast-350_normal.png",
"http://a3.twimg.com/profile_images/121630227/Droid_normal.jpg",
"http://a1.twimg.com/profile_images/957149154/twitterhalf_normal.jpg",
"http://a1.twimg.com/profile_images/97470808/icon_normal.png",
"http://a3.twimg.com/profile_images/511790713/AG.png",
"http://a3.twimg.com/profile_images/956404323/androinica-avatar_normal.png",
"http://a1.twimg.com/profile_images/909231146/Android_Biz_Man_normal.png",
"http://a3.twimg.com/profile_images/72774055/AndroidHomme-LOGO_normal.jpg",
"http://a1.twimg.com/profile_images/349012784/android_logo_small_normal.jpg",
"http://a1.twimg.com/profile_images/841338368/ea-twitter-icon.png",
"http://a3.twimg.com/profile_images/64827025/android-wallpaper6_2560x160_normal.png",
"http://a3.twimg.com/profile_images/77641093/AndroidPlanet_normal.png",
};
}
I found this particular code https://github.com/bauerca/drag-sort-listview in this url and in it I was able to add images also...
I'm also trying to make a custom layout. Added an image (from a 'drawable' folder) to 'layout/text_view.xml' (inserted in a LinearLayout). Changed StableArrayAdapter to extend BaseAdapter and rewrote getView (I think you can also make this with ArrayAdapter like https://stackoverflow.com/a/30270370/2914140). Then applied some changes for Lollipop from ListViewDraggingAnimation broken on Android 5 Lollipop and https://www.youtube.com/all_comments?v=_BZIvjMgH-Q. At least, static images are dragged along with text. When I change an ImageView to a WebVew, there are many errors and bugs.

Calling onDraw() method of a custom View in Android

I have created a CustomView for Calendar. I have an onDraw method to draw the text in the calendar. I want to change the color of the day Text when i click on it. How can i achieve it?
CalendarView.java :
package com.example.calendar_module;
import java.util.Calendar;
import android.app.ActionBar.LayoutParams;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.MonthDisplayHelper;
import android.view.MotionEvent;
import android.widget.ImageView;
public class CalendarView extends ImageView {
private static int WEEK_TOP_MARGIN = 0;
private static int WEEK_LEFT_MARGIN = 05;
private static int CELL_WIDTH = 20;
private static int CELL_HEIGH = 20;
private static int CELL_MARGIN_TOP = 05;
private static int CELL_MARGIN_LEFT = 29;
private static float CELL_TEXT_SIZE;
private static int CALENDAR_WIDTH;
private static int CALENDAR_HEIGHT;
private static final String TAG = "CalendarView";
private String[] mDayString = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
private Calendar mRightNow = null;
private Drawable mWeekTitle = null;
private Cell mToday = null;
private Cell[][] mCells = new Cell[6][7];
private Cell[] mDayCells = new Cell[7];
private OnCellTouchListener mOnCellTouchListener = null;
MonthDisplayHelper mHelper;
Drawable mDecoration = null;
public interface OnCellTouchListener {
public void onTouch(Cell cell);
}
public CalendarView(Context context) {
this(context, null);
}
public CalendarView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CalendarView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mDecoration = context.getResources().getDrawable(R.drawable.typeb_calendar_today);
initCalendarView();
}
private void initCalendarView() {
mRightNow = Calendar.getInstance();
// prepare static vars
Resources res = getResources();
WEEK_TOP_MARGIN = (int) res.getDimension(R.dimen.week_top_margin);
WEEK_LEFT_MARGIN = (int) res.getDimension(R.dimen.week_left_margin);
CELL_WIDTH = (int) res.getDimension(R.dimen.cell_width);
CELL_HEIGH = (int) res.getDimension(R.dimen.cell_heigh);
CELL_MARGIN_TOP = (int) res.getDimension(R.dimen.cell_margin_top);
CELL_MARGIN_LEFT = (int) res.getDimension(R.dimen.cell_margin_left);
// CALENDAR_HEIGHT = 700;
// CALENDAR_WIDTH = 700;
//
CALENDAR_HEIGHT = (int) res.getDimension(R.dimen.calendar_height);
CALENDAR_WIDTH = (int) res.getDimension(R.dimen.calendar_width);
System.out.println("Width and Hight :"+CALENDAR_WIDTH+" "+CALENDAR_HEIGHT);
System.out.println("Dimen Width and Height : "+R.dimen.calendar_width+" "+R.dimen.calendar_height);
CELL_TEXT_SIZE = res.getDimension(R.dimen.cell_text_size);
// set background
// setImageResource(R.drawable.background);
mWeekTitle = res.getDrawable(R.drawable.calendar_week);
mHelper = new MonthDisplayHelper(mRightNow.get(Calendar.YEAR), mRightNow.get(Calendar.MONTH));
}
private void initCells() {
class _calendar {
public int day;
public boolean thisMonth;
public _calendar(int d, boolean b) {
day = d;
thisMonth = b;
}
public _calendar(int d) {
this(d, false);
}
};
_calendar tmp[][] = new _calendar[6][7];
for(int i=0; i<tmp.length; i++) {
int n[] = mHelper.getDigitsForRow(i);
for(int d=0; d<n.length; d++) {
if(mHelper.isWithinCurrentMonth(i,d))
tmp[i][d] = new _calendar(n[d], true);
else
tmp[i][d] = new _calendar(n[d]);
}
}
Calendar today = Calendar.getInstance();
int thisDay = 0;
mToday = null;
if(mHelper.getYear()==today.get(Calendar.YEAR) && mHelper.getMonth()==today.get(Calendar.MONTH)) {
thisDay = today.get(Calendar.DAY_OF_MONTH);
}
// build cells
Rect Bound = new Rect(CELL_MARGIN_LEFT, CELL_MARGIN_TOP, CELL_WIDTH+CELL_MARGIN_LEFT, CELL_HEIGH+CELL_MARGIN_TOP);
// for( int i=0 ; i < 7 ; i++ )
// {
//
// mDayCells[i] = new Cell(mDayString[i],new Rect(Bound),CELL_TEXT_SIZE);
// Bound.offset(CELL_WIDTH, 0);
//
// }
//
// Bound.offset(0, CELL_HEIGH); // move to next row and first column
// Bound.left = CELL_MARGIN_LEFT;
// Bound.right = CELL_MARGIN_LEFT+CELL_WIDTH;
//
for(int week=0; week<mCells.length; week++) {
for(int day=0; day<mCells[week].length; day++)
{
if(tmp[week][day].thisMonth) {
if(day==0 || day==6 )
mCells[week][day] = new RedCell(tmp[week][day].day, new Rect(Bound), CELL_TEXT_SIZE);
else
mCells[week][day] = new Cell(tmp[week][day].day, new Rect(Bound), CELL_TEXT_SIZE);
} else {
mCells[week][day] = new GrayCell(tmp[week][day].day, new Rect(Bound), CELL_TEXT_SIZE);
}
Bound.offset(CELL_WIDTH, 0); // move to next column
// get today
if(tmp[week][day].day==thisDay && tmp[week][day].thisMonth) {
mToday = mCells[week][day];
mDecoration.setBounds(mToday.getBound());
}
}
Bound.offset(0, CELL_HEIGH); // move to next row and first column
Bound.left = CELL_MARGIN_LEFT;
Bound.right = CELL_MARGIN_LEFT+CELL_WIDTH;
}
}
#Override
public void onLayout(boolean changed, int left, int top, int right, int bottom) {
// Rect re = getDrawable().getBounds();
// WEEK_LEFT_MARGIN = CELL_MARGIN_LEFT = (right-left - re.width()) / 2;
// mWeekTitle.setBounds(WEEK_LEFT_MARGIN, WEEK_TOP_MARGIN, WEEK_LEFT_MARGIN+mWeekTitle.getMinimumWidth(), WEEK_TOP_MARGIN+mWeekTitle.getMinimumHeight());
initCells();
super.onLayout(changed, left, top, right, bottom);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
System.out.println("Width : "+CALENDAR_WIDTH);
System.out.println("Height : "+CALENDAR_HEIGHT);
setMeasuredDimension(CALENDAR_WIDTH, CALENDAR_HEIGHT);
// setMeasuredDimension(100,200);
}
public void setTimeInMillis(long milliseconds) {
mRightNow.setTimeInMillis(milliseconds);
initCells();
this.invalidate();
}
public int getYear() {
return mHelper.getYear();
}
public int getMonth() {
return mHelper.getMonth();
}
public void nextMonth() {
mHelper.nextMonth();
initCells();
invalidate();
}
public void previousMonth() {
mHelper.previousMonth();
initCells();
invalidate();
}
public boolean firstDay(int day) {
return day==1;
}
public boolean lastDay(int day) {
return mHelper.getNumberOfDaysInMonth()==day;
}
public void goToday() {
Calendar cal = Calendar.getInstance();
mHelper = new MonthDisplayHelper(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH));
initCells();
invalidate();
}
public Calendar getDate() {
return mRightNow;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if(mOnCellTouchListener!=null){
for(Cell[] week : mCells) {
for(Cell day : week) {
if(day.hitTest((int)event.getX(), (int)event.getY())) {
mOnCellTouchListener.onTouch(day);
}
}
}
}
return super.onTouchEvent(event);
}
public void setOnCellTouchListener(OnCellTouchListener p) {
mOnCellTouchListener = p;
}
#Override
protected void onDraw(Canvas canvas) {
// draw background
super.onDraw(canvas);
mWeekTitle.draw(canvas);
// draw cells
for(Cell[] week : mCells) {
for(Cell day : week) {
day.draw(canvas);
}
}
// draw today
if(mDecoration!=null && mToday!=null) {
mDecoration.draw(canvas);
}
}
public class GrayCell extends Cell {
public GrayCell(int dayOfMon, Rect rect, float s) {
super(dayOfMon, rect, s);
mPaint.setColor(Color.LTGRAY);
}
}
private class RedCell extends Cell {
public RedCell(int dayOfMon, Rect rect, float s) {
super(dayOfMon, rect, s);
mPaint.setColor(0xdddd0000);
}
}
}
Cell.java :
package com.example.calendar_module;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.util.Log;
public class Cell {
private static final String TAG = "Cell";
protected Rect mBound = null;
protected int mDayOfMonth = 1; // from 1 to 31
protected Paint mPaint = new Paint(Paint.SUBPIXEL_TEXT_FLAG
|Paint.ANTI_ALIAS_FLAG);
int dx, dy;
protected String mDayString;
private Cell cell ;
public Cell(int dayOfMon, Rect rect, float textSize, boolean bold) {
mDayOfMonth = dayOfMon;
mBound = rect;
mPaint.setTextSize(textSize);
mPaint.setColor(Color.BLACK);
if(bold) mPaint.setFakeBoldText(true);
dx = (int) mPaint.measureText(String.valueOf(mDayOfMonth)) / 2;
dy = (int) (-mPaint.ascent() + mPaint.descent()) / 2;
}
public Cell(String day,Rect rect,float textSize,boolean bold)
{
mDayString = day;
mBound = rect;
mPaint.setTextSize(textSize);
mPaint.setColor(Color.BLACK);
if(bold) mPaint.setFakeBoldText(true);
dx = (int) mPaint.measureText(String.valueOf(mDayString)) / 2;
dy = (int) (-mPaint.ascent() + mPaint.descent()) / 2;
}
public Cell(String day , Rect rect , float textSize , int newColor)
{
mDayString = day;
mBound = rect;
mPaint.setTextSize(textSize);
mPaint.setColor(newColor);
dx = (int) mPaint.measureText(String.valueOf(mDayString)) / 2;
dy = (int) (-mPaint.ascent() + mPaint.descent()) / 2;
}
public Cell(int dayOfMon, Rect rect, float textSize) {
this(dayOfMon, rect, textSize, false);
}
public Cell(String day,Rect rect,float textSize)
{
this(day,rect,textSize,false);
}
protected void draw(Canvas canvas) {
canvas.drawText(String.valueOf(mDayOfMonth), mBound.centerX() - dx, mBound.centerY() + dy, mPaint);
}
public int getDayOfMonth() {
return mDayOfMonth;
}
public boolean hitTest(int x, int y) {
return mBound.contains(x, y);
}
public Rect getBound() {
return mBound;
}
public String toString() {
return String.valueOf(mDayOfMonth)+"("+mBound.toString()+")";
}
}
CalendarActivity.java
package com.example.calendar_module;
import java.util.GregorianCalendar;
import com.example.calendar_module.CalendarView.OnCellTouchListener;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.DateUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class CalendarActivity extends Activity{
public static final String MIME_TYPE = "vnd.android.cursor.dir/vnd.example.calendar_module.date";
public static String mClickedDate, mClickedMonth;
CalendarView mView = null;
TextView mHit;
Handler mHandler = new Handler();
private Button mNextButton;
private Button mPreviousButton;
private TextView mMonthText ;
private int mMonthInt;
private ListView mEventListView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mView = (CalendarView)findViewById(R.id.calendar);
mEventListView = (ListView) findViewById(R.id.EventsList);
mEventListView.setAdapter(new BadgeAdapter(this));
mView.setOnCellTouchListener(new OnCellTouchListener() {
#Override
public void onTouch(Cell cell) {
TextView mMonthText = (TextView)findViewById(R.id.MonthText);
mClickedDate = ""+cell.getDayOfMonth();
mClickedMonth =""+mMonthText.getText();
// System.out.println("Clicked date is : "+mClickedDate+" "+mClickedMonth);
// startActivity(new Intent(CalendarActivity.this,Event.class));
// cell = new Cell(cell.getDayOfMonth(),new Rect(cell.getBound()),Color.MAGENTA);
}
});
mNextButton = (Button) findViewById(R.id.NextMonth);
mPreviousButton = (Button) findViewById(R.id.PreviousMonth);
mMonthText = (TextView) findViewById(R.id.MonthText);
mMonthText.setText(DateUtils.getMonthString(mView.getMonth(), DateUtils.LENGTH_LONG)+", "+mView.getYear());
// System.out.println("CurrentMonth is : "+mView.getMonth());
// if(getIntent().getAction().equals(Intent.ACTION_PICK))
// findViewById(R.id.hint).setVisibility(View.INVISIBLE);
mNextButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mView.nextMonth();
mMonthText.setText(DateUtils.getMonthString(mView.getMonth(), DateUtils.LENGTH_LONG)+", "+mView.getYear());
}
});
mPreviousButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mView.previousMonth();
mMonthText.setText(DateUtils.getMonthString(mView.getMonth(), DateUtils.LENGTH_LONG)+", "+mView.getYear());
}
});
System.out.println("Calendar View Height : "+mView.getHeight());
}
private class RedCell extends Cell {
public RedCell(Cell cell) {
super(cell.getDayOfMonth(),new Rect(cell.getBound()), R.dimen.cell_text_size);
mPaint.setColor(Color.RED);
}
}
}
Call mView.invalidate(); in your onClick() method for that View. This will call onDraw() (eventually), which will then run the drawing code for your view.

Categories

Resources