I am making a slot machine app and using kankan's wheel for the same. I want to modify the library such that when the rotation stops the item it will point shoud be the one that I set . I have done this but there is a glitch that shows that we have changed the actual image to the one that we want . How to achieve this?
Update:
I have researched a lot on this and if I am right , android scroll is based on duration and distance not items . From kankan's wheel library I can get current item .Now , I am trying to stop the animation as well as scroll , as soon as a certain duration has been reached and the item is the one that I want (through index) . But this is not working .Please help!!
GameActivity
public class GameActivity extends Activity {
float mDeviceDensity;
String mUuid, mTitle, mContent, mReward;
ImageButton play;
SlotMachineAdapter slotAdapter;
private List<HashMap<String, Object>> slotImages = new ArrayList<HashMap<String, Object>>();
ArrayList<String> imagesWinId = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_filler_up_game);
DisplayMetrics display = getResources().getDisplayMetrics();
mDeviceDensity = display.density;
slotAdapter = new SlotMachineAdapter(this);
getPassedData();
setSoundPlayer(R.raw.clicks,true);
initWheel(R.id.slot_1, false, 0);
initWheel(R.id.slot_2, false, 1);
initWheel(R.id.slot_3, true, 2);
play = (ImageButton) findViewById(R.id.btn_mix);
play.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
shuffle(R.id.slot_1, 5000);
shuffle(R.id.slot_2, 7000);
shuffle(R.id.slot_3, 9000);
}
});
}
protected ImageLoader imageLoader;
ArrayList<SlotItem> arrListSlotItems;
private void getPassedData() {
try {
mUuid = getIntent().getStringExtra(getString(R.string.FILLER_UP_UUID));
imageLoader = ImageLoader.getInstance();
Uuid slotImagesExtra = (Uuid) (getIntent()
.getSerializableExtra(getString(R.string.FILLER_UP_IMAGES)));
arrListSlotItems = slotImagesExtra.getArrSlotItemArray();
for (int i = 0; i < arrListSlotItems.size(); i++)
downloadSlotImages(arrListSlotItems.get(i).getSlotId(), arrListSlotItems.get(i).getImageUrl());
} catch (Exception e) {
e.printStackTrace();
}
}
// Wheel scrolled flag
private boolean wheelScrolled = false;
// Wheel scrolled listener
OnWheelScrollListener scrolledListener = new OnWheelScrollListener() {
public void onScrollingStarted(WheelView wheel) {
wheelScrolled = true;
}
public void onScrollingFinished(WheelView wheel) {
wheelScrolled = false;
setStatus(wheel.getId(), getWheel(wheel.getId()).getWinningIndex());
}
};
// Wheel changed listener
private OnWheelChangedListener changedListener = new OnWheelChangedListener() {
public void onChanged(WheelView wheel, int oldValue, int newValue) {
if (!wheelScrolled) {
}
}
};
/**
* Updates status
*/
private void updateStatus() {
myThread();
}
public void myThread(){
Thread th=new Thread(){
#Override
public void run(){
try
{
Thread.sleep(2000);
GameActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
showAlertDialogWithSingleButton(GameActivity.this, mTitle, mContent, success);
}
});
}catch (InterruptedException e) {
// TODO: handle exception
}
}
};
th.start();
}
android.content.DialogInterface.OnClickListener success = new android.content.DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (mContent != null && mContent.contains("again"))
startHomeActivity();
else
startNewsActivity();
}
};
private void startHomeActivity() {
}
private void startNewsActivity() {
}
android.content.DialogInterface.OnClickListener fail = new android.content.DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//
}
};
public void showAlertDialogWithSingleButton(final Activity ctx, final String title, final String message,
DialogInterface.OnClickListener onClickListener) {
// show dialog
}
private void initWheel(int id, boolean monitorScroll, int itemIndex) {
Random randomGenerator = new Random();
int index = randomGenerator.nextInt(arrListSlotItems.size());
WheelView wheel = getWheel(id);
wheel.setViewAdapter(slotAdapter);
wheel.setCurrentItem((index ));
wheel.setVisibleItems(1);
wheel.setWinningIndex(itemIndex);
wheel.addChangingListener(changedListener);
wheel.addScrollingListener(scrolledListener);
wheel.setCyclic(true);
wheel.setEnabled(false);
}
private WheelView getWheel(int id) {
return (WheelView) findViewById(id);
}
private void setStatus(int id, int item) {
int index = 0;
for (int i = 0; i < arrListSlotItems.size(); i++) {
SlotItem d = arrListSlotItems.get(i);
if (d.getSlotId() != 0 && d.getSlotId() == Integer.parseInt(imagesWinId.get(item)))
index = arrListSlotItems.indexOf(d);
}
getWheel(id).setCurrentItem(index, true);
if (id == R.id.slot_3) {
if(player.isPlaying())
{
stopBackgroundAudio();
}
updateStatus();
}
}
private void shuffle(int id, int duration) {
WheelView wheel = getWheel(id);
wheel.scroll(450 + (int) (Math.random() * 50), duration);
}
private class SlotMachineAdapter extends AbstractWheelAdapter {
final int IMAGE_WIDTH = getImageWidth(mDeviceDensity);
final int IMAGE_HEIGHT = getImageHeight(mDeviceDensity);
private Context context;
/**
* Constructor
*/
public SlotMachineAdapter(Context context) {
this.context = context;
}
/**
* Loads image from resources
*/
private Bitmap loadImage(Bitmap bitmap) {
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, IMAGE_WIDTH, IMAGE_HEIGHT, true);
return scaled;
}
#Override
public int getItemsCount() {
return slotImages.size();
}
// Layout params for image view
final LayoutParams params = new LayoutParams(IMAGE_WIDTH, IMAGE_HEIGHT);
#Override
public View getItem(int index, View cachedView, ViewGroup parent) {
ImageView img;
if (cachedView != null) {
img = (ImageView) cachedView;
} else {
img = new ImageView(context);
}
img.setPadding(0, 5, 0, 5);
img.setLayoutParams(params);
#SuppressWarnings("unchecked")
SoftReference<Bitmap> bitmapRef = (SoftReference<Bitmap>) slotImages.get(index).get("image");
Bitmap bitmap = bitmapRef.get();
if (bitmap == null) {
bitmap = loadImage(bitmap);
}
img.setImageBitmap(bitmap);
return img;
}
}
private int getImageWidth(float density) {
}
private int getImageHeight(float density) {
}
private void downloadSlotImages(final int id, String slotObj) {
//downloading slot images from server
}
}
This is the code. Through this code, when slot stops I want it to scroll some more untill it reaches the image position that I receaved from server. I can do this .But this is providing a lil glitch . Is there any way to stop scrolling when the image is reached as soon as certain duration is reached.
P.S. If you need anymore detail I can provide you.
P.P.S. Screenshots wont give you any detailed insight about the issue.
After days of searching I finally did it.All I had to do was set interpolater as LinearInterpolater and While setting setCurrentItem set animation as true.
Related
I am using Timertask for scrolling images with viewpager. I need to show all images after that it is automatically move to category wise (no click operation).
public class GalleryActviity extends AppCompatActivity {
Timer timer;
LinearLayout images_lay;
ArrayList<String> arraylist = new ArrayList<String>();
List<String> tempimages = new ArrayList<String>();
ViewPager mPager ;
private static int currentPage = 0
List<String> dealimages = new ArrayList<>();
ArrayList<DetailImage> detail_images = new ArrayList<DetailImage>();
#Override
protected void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
images_lay =(LinearLayout)findViewById(R.id.images_lay);
mPager = (ViewPager) findViewById(R.id.pager);
Intent in = getIntent();
Log.v("Tag_resid",""+in.getStringExtra("restid"));
String restid = in.getStringExtra("restid");
restaurntrestid(restid);
}
private void restaurntrestid(String restid) {
ServiceClient serviceClient = ServiceUtil.getServiceClient();
serviceClient.restaurntrestid(restid, restidcallback);
}
Callback<JsonObject> restidcallback = new Callback<JsonObject>() {
#Override
public void success(final JsonObject cusinerestaurantsinfo, Response response) {
imagesDeatail(cusinerestaurantsinfo);
}
#Override
public void failure(RetrofitError error) {
}
};
private void imagesDeatail(JsonObject cusinerestaurantsinfo) {
try {
JsonArray restaurant_imagesarray = cusinerestaurantsinfo.get("restaurant_images")
.getAsJsonArray();
for (int i = 0; i < restaurant_imagesarray.size(); i++) {
String url = restaurant_imagesarray.get(i).getAsJsonObject().get("url").getAsString();
String type = restaurant_imagesarray.get(i).getAsJsonObject().get("type").getAsString();
if(!arraylist.contains(type)){
arraylist.add(type);
// type means category like food, menu, logo...etc(dynamic data)
}
dealimages.add(url);
DetailImage detail = new DetailImage();
detail.setType(type);
detail.setUrl(url);
detail_images.add(detail);
}
mPager.setAdapter(new DealAdapter(GalleryActviity.this, dealimages));
imageRotator(1);
imageshow();
} catch (Exception e) {
e.printStackTrace();
}
}
public void imageRotator(int seconds) {
currentPage = 0;
timer = new Timer();
timer.scheduleAtFixedRate(new ImageRotateTask(), 0, seconds * 3000);
}
class ImageRotateTask extends TimerTask {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
if (currentPage == dealimages.size() ) {
timer.cancel();
//Something here
}
else {
mPager.setCurrentItem(currentPage++, true);
}
}
});
}
}
private void imageshow(){
for(int i = 0; i < arraylist.size(); i++) {
final Button txtview = new Button(this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
layoutParams.setMargins(0, 0, 0, 0);
if(i == 0){
txtview.setText("All");
txtview.setBackgroundColor(getResources().getColor(R.color.navigationBarwhite));
txtview.setTextColor(getResources().getColor(R.color.colorPrimary));
}
else {
txtview.setText(arraylist.get(i));
txtview.setBackgroundColor(getResources().getColor(R.color.navigationBarwhite));
txtview.setTextColor(getResources().getColor(R.color.navigationBarColor));
}
txtview.setLayoutParams(layoutParams);
txtview.setTextSize(12);
txtview.setAllCaps(false);
txtview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!txtview.getText().toString().equalsIgnoreCase("All")){
//image_display(txtview.getText().toString().trim());
txtview.setBackgroundColor(getResources().getColor(R.color.navigationBarwhite));
txtview.setTextColor(getResources().getColor(R.color.colorPrimary));
}
else if(txtview.getText().toString().equalsIgnoreCase("All")){
imageRotator(1);
mPager.setAdapter(new DealAdapter(GalleryActviity.this, dealimages));
}
}
});
images_lay.addView(txtview);
}
}
}
Here i am showing all the images in "ALL" section. how to show the remain images of every catgory. I added my screenshot which will show the images . "ALL" means every category type image will showing in this section.
Here i can showing all images in "ALL" Section, now how to move to automatically show the images based on category.
I've been searching everywhere and I can't find the answer. I'm simply trying to enable bluetooth in my fragment. I added the following to lines to my OnResume() callback:
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent,REQUEST_ENABLE_BT);
}
for some reason, the output just keeps saying, Activity.onPostResume() called over and over again and it actually locks out my UI. I was wondering if there's a solution?
Edit: AutoConnectFragment:
public class AutoConnectFragment extends Fragment {
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
private Toolbar mToolbar;
private CollapsingToolbarLayout collapsingToolbar;
private ImageView mBackArrow;
private Button mStartTiming;
private RecyclerView mLaserRecyclerView;
private LaserAdapter mAdapter;
private String mCurrentEvent;
private BluetoothAdapter mBluetoothAdapter;
private BluetoothLeScanner mBluetoothLeScanner;
private AutoConnectBLE mScanner;
private static boolean mIsLasersConnected;
private Drill mCurrentDrill;
private AutoConnectEventSelected mCallback;
private static final int REQUEST_ENABLE_BT = 3;
private static final int REQUEST_CODE_LOCATION = 42;
private boolean permissionChecked = false;
// Container Activity must implement this interface
public interface AutoConnectEventSelected {
public void onAutoConnectEventSelected(String event);
}
// private nested custom view holder class
public class LaserHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView mLaserName;
private Module mModule;
private ImageView mConnectIcon;
private ProgressBar mProgressBar;
public LaserHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.list_item_laser, parent, false));
itemView.setOnClickListener(this);
// grab the font
Typeface mont_reg = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Montserrat-Regular.ttf");
// grab the user name and change the font
mLaserName = (TextView) itemView.findViewById(R.id.laser_name);
mLaserName.setTypeface(mont_reg);
// grab the progress bar
mProgressBar = (ProgressBar) itemView.findViewById(R.id.progress_bar);
//grab the connect icon
mConnectIcon = (ImageView) itemView.findViewById(R.id.connect_icon);
}
public void bind(Module module) {
// set the text view to the module name
mModule = module;
mLaserName.setText(module.getName());
}
// if the user clicks on the connect laser
#Override
public void onClick(View v) {
if (mModule.getName().equals("RFID")) {
mProgressBar.setVisibility(View.VISIBLE);
mConnectIcon.setVisibility(View.GONE);
// mScanner.scanRFID(mCurrentDrill, mModule.getName(), v, getContext(), mAdapter,getAdapterPosition());
} else {
mProgressBar.setVisibility(View.VISIBLE);
mConnectIcon.setVisibility(View.GONE);
mScanner.scanLaser(v,mCurrentDrill, mModule.getName(),mAdapter,getAdapterPosition());
}
mAdapter.setCurrentPosition(getAdapterPosition());
}
}
public class LaserAdapter extends RecyclerView.Adapter<LaserHolder> {
private List<Module> mModules;
private String mCurrentMAC;
private int mCurrentPosition;
public LaserAdapter(List<Module> modules) {
mModules = modules;
}
#Override
public LaserHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
return new LaserHolder(layoutInflater, parent);
}
#Override
public void onBindViewHolder(LaserHolder holder, int position) {
Module module = mModules.get(position);
/* if a laser is already connected and
the user tries to connect the same laser to another position,
unconnect the previous connection
*/
if (!TextUtils.isEmpty(module.getMACaddress())){
if ( module.getMACaddress().equals(mCurrentMAC) && position != mCurrentPosition){
holder.mConnectIcon.setImageResource(R.drawable.ic_flash);
module.setMACaddress(null);
}
}
checkAllLasersConnected(mModules);
holder.bind(module);
}
#Override
public int getItemCount() {
return mModules.size();
}
public String getCurrentMAC() {
return mCurrentMAC;
}
public void setCurrentMAC(String currentMAC) {
mCurrentMAC = currentMAC;
}
public int getCurrentPosition() {
return mCurrentPosition;
}
public void setCurrentPosition(int currentPosition) {
mCurrentPosition = currentPosition;
}
public void checkAllLasersConnected(List<Module> modules){
int numLasersConnected = 0;
// checking to see if all of the lasers are connected
for (int i = 0; i < modules.size(); i++) {
System.out.println("Name: " + modules.get(i).getName() + " MAC :" + modules.get(i).getMACaddress());
if (modules.get(i).getMACaddress() == null) {
numLasersConnected++;
}
}
// if all of the lasers are connected, enabled the start timing button
if (numLasersConnected == 0) {
mStartTiming.setEnabled(true);
} else {
mStartTiming.setEnabled(false);
}
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_autoconnect, container, false);
// grab the recyclerview and set its layout manager
mLaserRecyclerView = (RecyclerView) view.findViewById(R.id.list_recycler_view);
mLaserRecyclerView.setLayoutManager((new LinearLayoutManager(getActivity())));
// update the UI ( recycler view )
updateUI(savedInstanceState);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// grab the views
collapsingToolbar = (CollapsingToolbarLayout) view.findViewById(R.id.collapsing_toolbar);
mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
mBackArrow = (ImageView) view.findViewById(R.id.back_arrow);
mStartTiming = (Button) view.findViewById(R.id.start_timing_button);
// disable the startTiming button until all of the lasers are connected
mStartTiming.setEnabled(false);
//Set toolbar title
collapsingToolbar.setTitle(getArguments().getString("Event") + " Connect");
// setting the text alignment
collapsingToolbar.setExpandedTitleColor(Color.WHITE);
collapsingToolbar.setCollapsedTitleGravity(Gravity.CENTER_HORIZONTAL);
collapsingToolbar.setCollapsedTitleTextColor(Color.WHITE);
collapsingToolbar.setExpandedTitleGravity(Gravity.CENTER_HORIZONTAL);
// set the font
Typeface mont_bold = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Montserrat-Bold.ttf");
Typeface mont_regular = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Montserrat-Regular.ttf");
collapsingToolbar.setExpandedTitleTypeface(mont_bold);
collapsingToolbar.setCollapsedTitleTypeface(mont_regular);
// set background color to dark grey
mToolbar.setBackgroundColor(getResources().getColor(R.color.darkGrey));
// set up bluetooth
mScanner = new AutoConnectBLE(getContext());
// collapsing tool bar effect ( explained in main activtiy)
AppBarLayout mAppBarLayout = (AppBarLayout) view.findViewById(R.id.app_bar_layout);
mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int i) {
//measuring for alpha
int toolBarHeight = mToolbar.getMeasuredHeight();
int appBarHeight = appBarLayout.getMeasuredHeight();
Float f = ((((float) appBarHeight - toolBarHeight) + i) / ((float) appBarHeight - toolBarHeight)) * 255;
if (Math.round(f) == 0) {
mToolbar.setBackgroundColor(getResources().getColor(R.color.darkGrey));
} else {
mToolbar.getBackground().setAlpha(0);
}
}
});
// if user clicks on the back arrow, go back to testing page
mBackArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment frag = new TestingFragment();
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container, frag, frag.getTag());
ft.addToBackStack(null);
ft.commit();
}
});
// if the user clicks on the start timing, goto the timing page
mStartTiming.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallback.onAutoConnectEventSelected(getArguments().getString("Event"));
}
});
}
#Override
public void onResume() {
super.onResume();
System.out.println("ON RESUME CALLED");
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
System.out.println("INTENT CALLED");
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
getActivity().startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
//
// if (!getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
// Toast.makeText(getActivity(), "No LE Support, Please install this app on another phone", Toast.LENGTH_SHORT).show();
// return;
// }
}
private void updateUI(Bundle savedInstanceState) {
List<Module> modules = null;
// check to see which event the user chose and grab the laser array list
switch (getArguments().getString("Event")) {
case "Dash":
Dash dash = Dash.getInstance();
modules = dash.getModules();
mCurrentDrill = dash;
break;
case "ProAgility":
ProAgility pa = ProAgility.getInstance();
modules = pa.getModules();
mCurrentDrill = pa;
break;
case "DashSplit":
DashSplit ds = DashSplit.getInstance();
modules = ds.getModules();
mCurrentDrill = ds;
break;
case "Flying40":
Flying40 f = Flying40.getInstance();
modules = f.getModules();
mCurrentDrill = f;
break;
case "Lap":
Lap l = Lap.getInstance();
modules = l.getModules();
mCurrentDrill = l;
break;
}
mAdapter = new LaserAdapter(modules);
mLaserRecyclerView.setAdapter(mAdapter);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
Activity a;
if (context instanceof Activity){
a = (Activity) context;
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (AutoConnectEventSelected) a;
} catch (ClassCastException e) {
throw new ClassCastException(a.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT) {
System.out.println(requestCode);
if (resultCode == Activity.RESULT_CANCELED) {
//Bluetooth not enabled.
getActivity().finish();
return;
} else {
return;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
BLE auto connect Scanner class:
public class AutoConnectBLE {
private BluetoothAdapter mBluetoothAdapter;
private BluetoothManager mBluetoothManager;
private BluetoothLeScanner mBluetoothLEScanner;
private ScanSettings mSettings;
private Context mContext;
private long mStartScanTimeStamp;
private long connectTimeStamp = 0L;
private class laserCallBack extends ScanCallback {
private Drill drill;
private AutoConnectFragment.LaserAdapter mAdapter;
private int position;
private boolean isConnected = false;
private long scanTimeStamp = 0L;
private long mElapsedTimeScanning;
private String mHex;
private long mLaserTime;
private String mBeefMessage;
private String name;
private ImageView mConnectIcon;
private ProgressBar mProgressBar;
public laserCallBack(View view, Drill drill,String name, AutoConnectFragment.LaserAdapter mAdapter, int position) {
super();
this.drill = drill;
this.mAdapter = mAdapter;
this.position = position;
this.name = name;
// grab views
mProgressBar = (ProgressBar) view.findViewById(R.id.progress_bar);
mConnectIcon = (ImageView) view.findViewById(R.id.connect_icon);
}
#Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
// grab a timestamp of when the scan starts
scanTimeStamp = SystemClock.uptimeMillis();
// if its been 3 seconds, without scanning then stop
mElapsedTimeScanning = (scanTimeStamp - mStartScanTimeStamp) / 1000;
// if the elapsed time is 3 seconds, then stop the scan
if (mElapsedTimeScanning >= 3) {
if (mConnectIcon.getVisibility() != View.VISIBLE) {
// if nothing was found, stop the circular progress bar and place the lightning bolt
mProgressBar.setVisibility(View.GONE);
mConnectIcon.setImageResource(R.drawable.ic_flash);
mConnectIcon.setVisibility(View.VISIBLE);
// clear out laser
ArrayList<Module> m = drill.getModules();
m.get(position).setMACaddress(null);
}
mAdapter.notifyDataSetChanged();
isConnected = false;
mBluetoothLEScanner.stopScan(this);
} else {
// grabbing important data from byte record
mHex = ConversionHelper
.bytesToHex(result.getScanRecord().getBytes());
mLaserTime = ConversionHelper.
hex2decimal(mHex.substring(24, 32));
mBeefMessage = mHex.substring(32, 36);
/* if there is no connection yet, and the beef message is preset,
and the laser time < 3 seconds,
and its atleast 3 seconds since another laser has advertised,
accept this new scan record as a potential new laser
*/
System.out.println("CONNECTION DELAY:" + (scanTimeStamp - connectTimeStamp));
if (!isConnected
&& ConversionHelper.hex2decimal(mBeefMessage) == 48879
&& mLaserTime < 3000
&& scanTimeStamp - connectTimeStamp > 3000) {
// set isConnected to true
isConnected = true;
// grab second timestamp - used so that people can't connect the same MAC for 2 lasers
connectTimeStamp = SystemClock.uptimeMillis();
System.out.println("CONNECT TIME STAMP" + connectTimeStamp);
// set the MAC address of the laser
drill.setMAC(name, result.getDevice().getAddress());
mAdapter.setCurrentMAC(result.getDevice().getAddress());
mAdapter.notifyDataSetChanged();
// check to see if this laser is connected to another position
// if the device finds a viable laser, replace the circular progress bar with a checkmark
mProgressBar.setVisibility(View.GONE);
mConnectIcon.setImageResource(R.drawable.ic_connected);
mConnectIcon.setVisibility(View.VISIBLE);
// notify the user that the start laser has been connected
Toast message = Toast.makeText(mContext, name + " Connected!", Toast.LENGTH_SHORT);
message.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
message.show();
isConnected = false;
mBluetoothLEScanner.stopScan(this);
}
}
}
}
public AutoConnectBLE(Context context) {
// grab context
mContext = context;
// grab BLE scanner
mBluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = mBluetoothManager.getAdapter();
mBluetoothLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
// set settings to LOW LATENCY
mSettings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build();
}
public void scanLaser(View view,Drill drill ,String name, final AutoConnectFragment.LaserAdapter mAdapter, int position) {
mStartScanTimeStamp = SystemClock.uptimeMillis();
mBluetoothLEScanner.startScan(new ArrayList<ScanFilter>(), mSettings,new laserCallBack(view, drill, name, mAdapter, position));
}
// public void scanRFID(final Drill drill, final String name, final View v, final Context context, final AutoConnectFragment.LaserAdapter mAdapter, final int position) {
//
// final ScanCallback RFIDCallBack = new ScanCallback() {
// #Override
// public void onScanResult(int callbackType, ScanResult result) {
// super.onScanResult(callbackType, result);
//
// // grab a timestamp
// scanTimeStamp = SystemClock.uptimeMillis();
//
//
// String hex = ConversionHelper
// .bytesToHex(result.getScanRecord().getBytes());
// String RFIDBeefMessage = hex.substring(36, 40);
// System.out.println(hex);
//
// // if its been 3 seconds, without connecting then stop
// mElapsedTimeScanning = (scanTimeStamp - mStartScanTimeStamp) / 1000;
// if (mElapsedTimeScanning == 3) {
// ImageView mConnectIcon = (ImageView) v.findViewById(R.id.connect_icon);
// if (mConnectIcon.getVisibility() != View.VISIBLE) {
//
// // if nothing was found, stop the circular progress bar and place the lightning bolt
// ProgressBar mProgressBar = (ProgressBar) v.findViewById(R.id.progress_bar);
// mProgressBar.setVisibility(View.GONE);
// mConnectIcon.setImageResource(R.drawable.ic_flash);
// mConnectIcon.setVisibility(View.VISIBLE);
//
// }
// System.out.println("STOPPED SCANNING");
// mBluetoothLEScanner.stopScan(this);
// isConnected = false;
// }
//
// // RFID
// if (!isConnected && RFIDBeefMessage.equals("BEEF")) {
// isConnected = true;
// mBluetoothLEScanner.stopScan(this);
//
// // set the MAC address of the laser
// String MACAddress = result.getDevice().getAddress();
// drill.setMAC(name, MACAddress);
// // notify the user that the start laser has been connected
//
// // if the device finds a viable laser, replace the circular progress bar with a checkmark
// ImageView mConnectIcon = (ImageView) v.findViewById(R.id.connect_icon);
// ProgressBar mProgressBar = (ProgressBar) v.findViewById(R.id.progress_bar);
// mProgressBar.setVisibility(View.GONE);
// mConnectIcon.setImageResource(R.drawable.ic_connected);
// mConnectIcon.setVisibility(View.VISIBLE);
// Toast message = Toast.makeText(context, name + " Connected!", Toast.LENGTH_SHORT);
// message.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
// message.show();
//
// }
//
// }
//
// };
// mStartScanTimeStamp = SystemClock.uptimeMillis();
// mBluetoothLEScanner.startScan(new ArrayList<ScanFilter>(), mSettings, RFIDCallBack);
//
//
// }
}
Use below code to enable your bluetooth
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(!mBluetoothAdapter.isEnabled()){
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(getActivity());
alertBuilder.setCancelable(true);
alertBuilder.setMessage("Do you want to enable bluetooth");
alertBuilder.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mBluetoothAdapter.enable();
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
}
Just add a manifest permission for Bluetooth access.
<uses-permission android:name="android.permission.BLUETOOTH"/>
and add this snippet in your fragment, for run time permission allowance.
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.BLUETOOTH)
!= PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(((Activity)getContext()),
new String[]{Manifest.permission.BLUETOOTH}, REQUEST_CODE);
}
The snippet automatically launch an alert for Bluetooth access.
First get a BluetoothAdapter object
BluetoothAdapter adapter = BluetoothAdapter.getDefaultBluetoothAdapter();
if(adapter != null){
adapter.enable();
}
Using above code you can enable Bluetooth without user permission.I hope this code will help you
Hi I am new in android and in my app I have a lot of images in my ArrayList that 's
why I want to swipe those images automatically for every 3 seconds with help of Timetasker and this process is continuously need to repeating up to we close app. Can some body help me please
MainActivity:-
public class MainActivity extends AppCompatActivity {
ViewPager viewPager;
Integer[] imageId = {R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4};
String[] imagesName = {"image1","image2","image3","image4"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
viewPager = (ViewPager) findViewById(R.id.viewPager);
PagerAdapter adapter = new CustomAdapter(MainActivity.this,imageId,imagesName);
viewPager.setAdapter(adapter);
}
}
CustomAdapter:-
public class CustomAdapter extends PagerAdapter{
private Activity activity;
private Integer[] imagesArray;
private String[] namesArray;
public CustomAdapter(Activity activity,Integer[] imagesArray,String[] namesArray){
this.activity = activity;
this.imagesArray = imagesArray;
this.namesArray = namesArray;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater inflater = ((Activity)activity).getLayoutInflater();
View viewItem = inflater.inflate(R.layout.image_item, container, false);
ImageView imageView = (ImageView) viewItem.findViewById(R.id.imageView);
imageView.setImageResource(imagesArray[position]);
TextView textView1 = (TextView) viewItem.findViewById(R.id.textview);
textView1.setText(namesArray[position]);
((ViewPager)container).addView(viewItem);
return viewItem;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return imagesArray.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
// TODO Auto-generated method stub
return view == ((View)object);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// TODO Auto-generated method stub
((ViewPager) container).removeView((View) object);
}
}
Your question is already answered here
Add this in your MainActivity.java
//...
int currentPage = 0;
Timer timer;
final long DELAY_MS = 500;//delay in milliseconds before task is to be executed
final long PERIOD_MS = 3000; // time in milliseconds between successive task executions.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
viewPager = (ViewPager) findViewById(R.id.viewPager);
PagerAdapter adapter = new CustomAdapter(MainActivity.this,imageId,imagesName);
viewPager.setAdapter(adapter);
/*After setting the adapter use the timer */
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == NUM_PAGES-1) {
currentPage = 0;
}
viewPager.setCurrentItem(currentPage++, true);
}
};
timer = new Timer(); // This will create a new Thread
timer.schedule(new TimerTask() { // task to be scheduled
#Override
public void run() {
handler.post(Update);
}
}, DELAY_MS, PERIOD_MS);
}
Here is the code for the automatic scroll the viewpager item:
public class MainActivity extends AppCompatActivity {
AutoScrollViewPager viewPager;
Integer[] imageId = {R.drawable.commitementlogo, R.drawable.like, R.drawable.like_select, R.drawable.plus};
String[] imagesName = {"image1","image2","image3","image4"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager= (AutoScrollViewPager) findViewById(R.id.viewpager);
viewPager.startAutoScroll();
viewPager.setInterval(3000);
viewPager.setCycle(true);
viewPager.setStopScrollWhenTouch(true);
PagerAdapter adapter = new CustomAdapter(MainActivity.this,imageId,imagesName);
viewPager.setAdapter(adapter);
}
}
Here AutoscrollViewpager class:
public class AutoScrollViewPager extends ViewPager {
public static final int DEFAULT_INTERVAL = 1500;
public static final int LEFT = 0;
public static final int RIGHT = 1;
/** do nothing when sliding at the last or first item **/
public static final int SLIDE_BORDER_MODE_NONE = 0;
/** cycle when sliding at the last or first item **/
public static final int SLIDE_BORDER_MODE_CYCLE = 1;
/** deliver event to parent when sliding at the last or first item **/
public static final int SLIDE_BORDER_MODE_TO_PARENT = 2;
/** auto scroll time in milliseconds, default is {#link #DEFAULT_INTERVAL} **/
private long interval = DEFAULT_INTERVAL;
/** auto scroll direction, default is {#link #RIGHT} **/
private int direction = RIGHT;
/** whether automatic cycle when auto scroll reaching the last or first item, default is true **/
private boolean isCycle = true;
/** whether stop auto scroll when touching, default is true **/
private boolean stopScrollWhenTouch = true;
/** how to process when sliding at the last or first item, default is {#link #SLIDE_BORDER_MODE_NONE} **/
private int slideBorderMode = SLIDE_BORDER_MODE_NONE;
/** whether animating when auto scroll at the last or first item **/
private boolean isBorderAnimation = true;
/** scroll factor for auto scroll animation, default is 1.0 **/
private double autoScrollFactor = 1.0;
/** scroll factor for swipe scroll animation, default is 1.0 **/
private double swipeScrollFactor = 1.0;
private Handler handler;
private boolean isAutoScroll = false;
private boolean isStopByTouch = false;
private float touchX = 0f, downX = 0f;
private CustomDurationScroller scroller = null;
public static final int SCROLL_WHAT = 0;
public AutoScrollViewPager(Context paramContext) {
super(paramContext);
init();
}
public AutoScrollViewPager(Context paramContext, AttributeSet paramAttributeSet) {
super(paramContext, paramAttributeSet);
init();
}
private void init() {
handler = new MyHandler(this);
setViewPagerScroller();
}
/**
* start auto scroll, first scroll delay time is {#link #getInterval()}
*/
public void startAutoScroll() {
isAutoScroll = true;
sendScrollMessage((long)(interval + scroller.getDuration() / autoScrollFactor * swipeScrollFactor));
}
/**
* start auto scroll
*
* #param delayTimeInMills first scroll delay time
*/
public void startAutoScroll(int delayTimeInMills) {
isAutoScroll = true;
sendScrollMessage(delayTimeInMills);
}
/**
* stop auto scroll
*/
public void stopAutoScroll() {
isAutoScroll = false;
handler.removeMessages(SCROLL_WHAT);
}
/**
* set the factor by which the duration of sliding animation will change while swiping
*/
public void setSwipeScrollDurationFactor(double scrollFactor) {
swipeScrollFactor = scrollFactor;
}
/**
* set the factor by which the duration of sliding animation will change while auto scrolling
*/
public void setAutoScrollDurationFactor(double scrollFactor) {
autoScrollFactor = scrollFactor;
}
private void sendScrollMessage(long delayTimeInMills) {
/** remove messages before, keeps one message is running at most **/
handler.removeMessages(SCROLL_WHAT);
handler.sendEmptyMessageDelayed(SCROLL_WHAT, delayTimeInMills);
}
/**
* set ViewPager scroller to change animation duration when sliding
*/
private void setViewPagerScroller() {
try {
Field scrollerField = ViewPager.class.getDeclaredField("mScroller");
scrollerField.setAccessible(true);
Field interpolatorField = ViewPager.class.getDeclaredField("sInterpolator");
interpolatorField.setAccessible(true);
scroller = new CustomDurationScroller(getContext(), (Interpolator)interpolatorField.get(null));
scrollerField.set(this, scroller);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* scroll only once
*/
public void scrollOnce() {
PagerAdapter adapter = getAdapter();
int currentItem = getCurrentItem();
int totalCount;
if (adapter == null || (totalCount = adapter.getCount()) <= 1) {
return;
}
int nextItem = (direction == LEFT) ? --currentItem : ++currentItem;
if (nextItem < 0) {
if (isCycle) {
setCurrentItem(totalCount - 1, isBorderAnimation);
}
} else if (nextItem == totalCount) {
if (isCycle) {
setCurrentItem(0, isBorderAnimation);
}
} else {
setCurrentItem(nextItem, true);
}
}
/**
* <ul>
* if stopScrollWhenTouch is true
* <li>if event is down, stop auto scroll.</li>
* <li>if event is up, start auto scroll again.</li>
* </ul>
*/
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
int action = ev.getActionMasked();
if (stopScrollWhenTouch) {
if ((action == MotionEvent.ACTION_DOWN) && isAutoScroll) {
isStopByTouch = true;
stopAutoScroll();
} else if (ev.getAction() == MotionEvent.ACTION_UP && isStopByTouch) {
startAutoScroll();
}
}
if (slideBorderMode == SLIDE_BORDER_MODE_TO_PARENT || slideBorderMode == SLIDE_BORDER_MODE_CYCLE) {
touchX = ev.getX();
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
downX = touchX;
}
int currentItem = getCurrentItem();
PagerAdapter adapter = getAdapter();
int pageCount = adapter == null ? 0 : adapter.getCount();
/**
* current index is first one and slide to right or current index is last one and slide to left.<br/>
* if slide border mode is to parent, then requestDisallowInterceptTouchEvent false.<br/>
* else scroll to last one when current item is first one, scroll to first one when current item is last
* one.
*/
if ((currentItem == 0 && downX <= touchX) || (currentItem == pageCount - 1 && downX >= touchX)) {
if (slideBorderMode == SLIDE_BORDER_MODE_TO_PARENT) {
getParent().requestDisallowInterceptTouchEvent(false);
} else {
if (pageCount > 1) {
setCurrentItem(pageCount - currentItem - 1, isBorderAnimation);
}
getParent().requestDisallowInterceptTouchEvent(true);
}
return super.dispatchTouchEvent(ev);
}
}
getParent().requestDisallowInterceptTouchEvent(true);
return super.dispatchTouchEvent(ev);
}
private static class MyHandler extends Handler {
private final WeakReference<AutoScrollViewPager> autoScrollViewPager;
public MyHandler(AutoScrollViewPager autoScrollViewPager) {
this.autoScrollViewPager = new WeakReference<AutoScrollViewPager>(autoScrollViewPager);
}
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case SCROLL_WHAT:
AutoScrollViewPager pager = this.autoScrollViewPager.get();
if (pager != null) {
pager.scroller.setScrollDurationFactor(pager.autoScrollFactor);
pager.scrollOnce();
pager.scroller.setScrollDurationFactor(pager.swipeScrollFactor);
pager.sendScrollMessage(pager.interval + pager.scroller.getDuration());
}
default:
break;
}
}
}
/**
* get auto scroll time in milliseconds, default is {#link #DEFAULT_INTERVAL}
*
* #return the interval
*/
public long getInterval() {
return interval;
}
/**
* set auto scroll time in milliseconds, default is {#link #DEFAULT_INTERVAL}
*
* #param interval the interval to set
*/
public void setInterval(long interval) {
this.interval = interval;
}
/**
* get auto scroll direction
*
* #return {#link #LEFT} or {#link #RIGHT}, default is {#link #RIGHT}
*/
public int getDirection() {
return (direction == LEFT) ? LEFT : RIGHT;
}
/**
* set auto scroll direction
*
* #param direction {#link #LEFT} or {#link #RIGHT}, default is {#link #RIGHT}
*/
public void setDirection(int direction) {
this.direction = direction;
}
/**
* whether automatic cycle when auto scroll reaching the last or first item, default is true
*
* #return the isCycle
*/
public boolean isCycle() {
return isCycle;
}
/**
* set whether automatic cycle when auto scroll reaching the last or first item, default is true
*
* #param isCycle the isCycle to set
*/
public void setCycle(boolean isCycle) {
this.isCycle = isCycle;
}
/**
* whether stop auto scroll when touching, default is true
*
* #return the stopScrollWhenTouch
*/
public boolean isStopScrollWhenTouch() {
return stopScrollWhenTouch;
}
/**
* set whether stop auto scroll when touching, default is true
*
* #param stopScrollWhenTouch
*/
public void setStopScrollWhenTouch(boolean stopScrollWhenTouch) {
this.stopScrollWhenTouch = stopScrollWhenTouch;
}
/**
* get how to process when sliding at the last or first item
*
* #return the slideBorderMode {#link #SLIDE_BORDER_MODE_NONE}, {#link #SLIDE_BORDER_MODE_TO_PARENT},
* {#link #SLIDE_BORDER_MODE_CYCLE}, default is {#link #SLIDE_BORDER_MODE_NONE}
*/
public int getSlideBorderMode() {
return slideBorderMode;
}
/**
* set how to process when sliding at the last or first item
*
* #param slideBorderMode {#link #SLIDE_BORDER_MODE_NONE}, {#link #SLIDE_BORDER_MODE_TO_PARENT},
* {#link #SLIDE_BORDER_MODE_CYCLE}, default is {#link #SLIDE_BORDER_MODE_NONE}
*/
public void setSlideBorderMode(int slideBorderMode) {
this.slideBorderMode = slideBorderMode;
}
/**
* whether animating when auto scroll at the last or first item, default is true
*
* #return
*/
public boolean isBorderAnimation() {
return isBorderAnimation;
}
/**
* set whether animating when auto scroll at the last or first item, default is true
*
* #param isBorderAnimation
*/
public void setBorderAnimation(boolean isBorderAnimation) {
this.isBorderAnimation = isBorderAnimation;
}
}
here CustomDurationScroller class:
public class CustomDurationScroller extends Scroller {
private double scrollFactor = 1;
public CustomDurationScroller(Context context) {
super(context);
}
public CustomDurationScroller(Context context, Interpolator interpolator) {
super(context, interpolator);
}
public void setScrollDurationFactor(double scrollFactor) {
this.scrollFactor = scrollFactor;
}
#Override
public void startScroll(int startX, int startY, int dx, int dy, int duration) {
super.startScroll(startX, startY, dx, dy, (int)(duration * scrollFactor));
}
}
and set the adapter same as you previously set.
Here is the total code using TimerTask:
public class MainActivity extends AppCompatActivity {
ViewPager viewPager;
Integer[] imageId = {R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4};
String[] imagesName = {"image1","image2","image3","image4"};
Timer timer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
viewPager = (ViewPager) findViewById(R.id.viewPager);
PagerAdapter adapter = new CustomAdapter(MainActivity.this,imageId,imagesName);
viewPager.setAdapter(adapter);
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
viewPager.post(new Runnable(){
#Override
public void run() {
viewPager.setCurrentItem((viewPager.getCurrentItem()+1)%imageId.length);
}
});
}
};
timer = new Timer();
timer.schedule(timerTask, 3000, 3000);
}
#Override
protected void onDestroy() {
timer.cancel();
super.onDestroy();
}
}
Create handler in activity, then schedule a task. I think Handler is enough for this small task. Don't go for timer.
Runnable timeCounter = new Runnable() {
#Override
public void run() {
if((currentIndex+1)>imageId.length() ){
currentIndex=0;
}else{
currentIndex++;
}
ViewPager.setCurrentItem(currentIndex);
handler.postDelayed(timeCounter, 3*1000);
}
};
handler.postDelayed(timeCounter, 3*1000);
then in onDestroy() or where ever you want to stop
handler.removeCallbacks(timeCounter);
Another version of the answer:-
private int currentPage = -1;
// start auto scroll of viewpager
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
viewPager.setCurrentItem(++currentPage, true);
// go to initial page i.e. position 0
if (currentPage == NUM_PAGES -1) {
currentPage = -1;
// ++currentPage will make currentPage = 0
}
}
};
timer = new Timer(); // This will create a new Thread
timer.schedule(new TimerTask() { // task to be scheduled
#Override
public void run() {
handler.post(Update);
}
}, 500, 1500);
a simple edit to #L. Swifter's code snippet for the ones wondering about variables, I wrapped it all in a method which you can add to your activity after setting the adapter
private void automateViewPagerSwiping() {
final long DELAY_MS = 500;//delay in milliseconds before task is to be executed
final long PERIOD_MS = 3000; // time in milliseconds between successive task executions.
final Handler handler = new Handler();
final Runnable update = new Runnable() {
public void run() {
if (viewPager.getCurrentItem() == adapter.getCount() - 1) { //adapter is your custom ViewPager's adapter
viewPager.setCurrentItem(0);
}
else {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true);
}
}
};
timer = new Timer(); // This will create a new Thread
timer.schedule(new TimerTask() { // task to be scheduled
#Override
public void run() {
handler.post(update);
}
}, DELAY_MS, PERIOD_MS);
}
For a simple solution to show a series of images automatically try the ViewFlipper in your xml file. Not suitable for all purposes, but I found it to be a useful solution to something I was putting together.
<ViewFlipper
android:id="#+id/viewflipper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoStart="true"
android:flipInterval="2000" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/picture1" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/picture2" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/picture3" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/picture4" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/picture5" />
Auto swipe ViewPager in Kotlin, simple and easy code.(if you have only 2 page)
val handler = Handler()
val update = Runnable {
viewPager.setCurrentItem(currentPage % 2, true);
currentPage++
}
var timer = Timer()// This will create a new Thread
timer!!.schedule(object : TimerTask() {
override fun run() {
handler.post(update)
}
}, 500(DELAY_MS), 3000(PERIOD_MS))
try this code:
In MainActivity -
int currentIndex=0; //for tracking current item
Create and set your TimerTask as per your requirement then in run() of TimerTask:
public void run() {
if((currentIndex+1)>imageId.length() ){
currentIndex=0;
}else{
currentIndex++;
}
ViewPager.setCurrentItem(currentIndex);
}
int ci=0;
java.util.Timer timer;
timer=new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
viewPager.post(new Runnable() {
#Override
public void run() {
Log.d("viewPager",""+ci);
viewPager.setCurrentItem(ci%7);
ci++;
}
});
}
},1000,5000);
it updates every 5seconds(5000)
You can use android TabLayout for indicators, ViewPager for slide screen and TimerTask to slide automatic
please check this link for step by step guideline and demo
CLICK HERE
Try this in your onCreate() method
final Handler handler = new Handler();
Timer timer = new Timer();
final Runnable runnable = new Runnable() {
public void run() {
int currentPage=viewPager.getCurrentItem();
//return to first page, if current page is last page
if (currentPage == titleNames.length-1) {
currentPage = -1;
}
viewPager.setCurrentItem(++currentPage, true);
}
};
timer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(runnable);
}
},DELAY,PERRIOD)
using Kotlin coroutine
val totalPages = 3
CoroutineScope(Dispatchers.Main).launch {
while (isActive) {
delay(1500)
if (viewPager.currentItem + 1 > totalPages-1) {
viewPager.currentItem = 0
} else {
viewPager.currentItem++
}
}
}
Try to use ViewFlipper instead of viewpager
Layout xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ViewFlipper
android:id="#+id/imageFrames"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#android:drawable/screen_background_dark" >
</ViewFlipper>
<Button
android:id="#+id/slideShowBtn"
android:layout_width="200dp"
android:layout_height="wrap_content"
Activity
public class SlideShowActivity extends Activity {
ViewFlipper imageFrame;
Button slideShowBtn;
Handler handler;
Runnable runnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.photo_slideshow_main);
imageFrame = (ViewFlipper) findViewById(R.id.imageFrames);
//get sd card path for images
File parentFolder = new
File(Environment.getExternalStorageDirectory()
.getAbsolutePath()
+ "/images");
addFlipperImages(imageFrame, parentFolder);
handler = new Handler();
imageFrame.setOnClickListener(SlideShowActivity.this);
slideShowBtn = (Button) findViewById(R.id.slideShowBtn);
slideShowBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
runnable = new Runnable() {
#Override
public void run() {
handler.postDelayed(runnable, 3000);
imageFrame.showNext();
}
};
handler.postDelayed(runnable, 500);
}
});
}
private void addFlipperImages(ViewFlipper flipper, File parent) {
int imageCount = parent.listFiles().length;
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.FILL_PARENT);
for (int count = 0; count < imageCount - 1; count++) {
ImageView imageView = new ImageView(this);
Bitmap imbm = BitmapFactory.decodeFile(parent.listFiles()[count]
.getAbsolutePath());
imageView.setImageBitmap(imbm);
imageView.setLayoutParams(params);
flipper.addView(imageView);
}
}
}
#Override
public void onClick(View view) {
}
}
I write the custom ImageView to display an animation with list of bitmaps. Here is my source code:
public class CustomImageView extends ImageView {
public CustomImageView(Context context) {
super(context);
}
public void startAnimation(List<BitmapDrawable> arrBitmapDelay, int[] durations) {
if (arrBitmapDelay.size() > 1 && arrBitmapDelay.size() == durations.length) {
final AnimationDrawable oAnimation = new AnimationDrawable();
oAnimation.setOneShot(false);
int i = 0;
for (BitmapDrawable oBitmapDelay : arrBitmapDelay) {
oAnimation.addFrame(oBitmapDelay, durations[i]);
i++;
}
if(getContext() instanceof Activity)
if(((Activity)getContext()).isFinishing())
return;
if(oAnimation.getNumberOfFrames()<=0) return;
setImageDrawable(oAnimation);
post(new Runnable() {
#Override
public void run() {
oAnimation.start();
}
});
}
}
}
And the result: https://goo.gl/photos/FSC5RaEE2ajfe23v6
You can see, it loop correctly time, but sometimes it flashing... Please help!
EDIT
I add code of reading list bitmap.
public void decodeAndShow() {
List<Bitmap> bitmaps = new ArrayList<>();
int[] duration = new int[20];
for (int i=0; i<20; i++) {
bitmaps.add(BitmapFactory.decodeFile(new File(getContext().getCacheDir(), "bitmapsample"+i+".png").getAbsolutePath()));
duration[i] = 100;
}
img.startAnimation(bitmaps, duration);
}
Sorry, because my project is too much complicated to copy here.
Add android:hardwareAccelerated="true" to your manifest, either for the or the . This ensures that your app uses the devices graphics card and should help with your animation.
I fixed by myself with a cheat. I don't know why it's OK.
This is my code:
public class CustomImageView extends ImageView {
private Runnable runningAnimation;
public CustomImageView(Context context) {
super(context);
}
public void startAnimation(List<BitmapDrawable> arrBitmapDelay, int[] durations) {
if(runningAnimation != null) {
this.removeCallbacks(runningAnimation);
}
if (arrBitmapDelay.size() > 1 && arrBitmapDelay.size() == durations.length) {
final AnimationDrawable oAnimation = new AnimationDrawable();
oAnimation.setOneShot(false);
int i = 0;
for (BitmapDrawable oBitmapDelay : arrBitmapDelay) {
oAnimation.addFrame(oBitmapDelay, durations[i]);
i++;
}
if(getContext() instanceof Activity)
if(((Activity)getContext()).isFinishing())
return;
if(oAnimation.getNumberOfFrames()<=0) return;
setImageDrawable(oAnimation);
runningAnimation = new Runnable() {
#Override
public void run() {
oAnimation.start();
}
}
post(runningAnimation);
}
}
}
I've got a strange problem, a Dialog being created and called for "show()" but not being visible in my activity...
The thing is it goes through the call "show", I've seen it in the debugger, but nothing...
here is the code:
protected void initializeSpinners() {
spnPlayLists = (Spinner) findViewById(R.id.spnLists);
spnProviders = (Spinner) findViewById(R.id.spnProvider);
spnProviders.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> _spinner, View _parent,
int _pos, long _id) {
if (_spinner == spnProviders) {
String[] playListsId = core.getAllPlayListsFrom(_pos);
int items = playListsId.length;
**showProgressDialog(items);**
String[] playListsNames = new String[items];
String[] playListsThumbs = new String[items];
playLists = new PlayList[items];
for (int i = 0; i < items; i++) {
String id = playListsId[i];
PlayList playList = core.getPlayList(id, true);
playLists[i] = playList;
playListsNames[i] = playList.title;
playListsThumbs[i] = playList.thumb;
handle.sendEmptyMessage(i);
}
loadPlayLists(playListsNames, playListsThumbs);
myPd_bar.dismiss();
}
}
#Override
public void onNothingSelected(AdapterView<?> _arg0) {
}
});
ProvidersArrayAdapter providersAdapter = new ProvidersArrayAdapter(this);
spnProviders.setAdapter(providersAdapter);
}
and the function called up:
private void showProgressDialog(int _items) {
handle = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
myPd_bar.setProgress(msg.what + 1);
}
};
myPd_bar = new ProgressDialog(Intro.this);
myPd_bar.setMessage("Loading....");
myPd_bar.setTitle("Please Wait..");
myPd_bar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
myPd_bar.setProgress(0);
myPd_bar.setMax(_items);
**myPd_bar.show();**
}
what am I doing bad...?
It is possible that your dialog is getting dismissed before it appears. Basically your loop is not going long enough for the view to appear.
Have you tried to comment out the dismiss line and see if it appear then?
Finally I realized. I was holding the activity thread in the spinner so it won't show anything until it finishes!
here is my solution, using an asyntask (properly, I was using them badly on the playlist load, and blocking)
protected void setupDialog() {
handle = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what < 0){
loadPlayLists(playListsNames, playListsThumbs);
myPd_bar.dismiss();
} else {
myPd_bar.setProgress(msg.what + 1);
}
}
};
myPd_bar = new ProgressDialog(Intro.this);
myPd_bar.setMessage(WAIT_MESSAGE);
myPd_bar.setTitle(WAIT_TITLE);
myPd_bar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
myPd_bar.setProgress(0);
}
protected void initializeSpinners() {
spnPlayLists = (Spinner) findViewById(R.id.spnLists);
spnProviders = (Spinner) findViewById(R.id.spnProvider);
spnProviders.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> _spinner, View _parent,
int _pos, long _id) {
if (_spinner == spnProviders) {
String[] playListsId = core.getAllPlayListsFrom(_pos);
int items = playListsId.length;
myPd_bar.setMax(items);
myPd_bar.show();
new AsyncTask<String[], Integer, Long>(){
#Override
protected Long doInBackground(String[]... _playListsId) {
int items = _playListsId[0].length;
playListsNames = new String[items];
playListsThumbs = new String[items];
playLists = new PlayList[items];
for (int i = 0; i < items; i++) {
String id = _playListsId[0][i];
PlayList playList = core.getPlayList(id, true);
playLists[i] = playList;
playListsNames[i] = playList.title;
playListsThumbs[i] = playList.thumb;
publishProgress(i);
}
return null;
}
#Override
protected void onProgressUpdate(Integer... _progress) {
handle.sendEmptyMessage(_progress[0]);
}
#Override
protected void onPostExecute(Long _result) {
handle.sendEmptyMessage(-1);
}
}.execute(playListsId);
}
}
#Override
public void onNothingSelected(AdapterView<?> _arg0) {
}
});
ProvidersArrayAdapter providersAdapter = new ProvidersArrayAdapter(this);
spnProviders.setAdapter(providersAdapter);
}