Implementing JazzyViewPager - animation

Branching from my other question from HERE, I want to try and implement JazzyViewPager. I tried following the setup instructions along with a few other posts on this site, but was unable to get it working, just did the ViewPager action.
Below is the relevant untouched (sync issue with AIDE erased previous) code I'm working with.
MainActivity:
pageAdapter = new MyPagerAdapter(getSupportFragmentManager());
final ViewPager pager = (ViewPager) findViewById(R.id.myViewPager);
pager.setAdapter(pageAdapter);
pager.setOffscreenPageLimit(1);
pager.setPageMarginDrawable(R.color.pager_bg);
MyPagerAdapter:
package com.chris.myapp;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.chris.myapp.fragment.Shoutbox;
import com.chris.myapp.fragment.WebViewFragment;
import java.util.ArrayList;
import java.util.List;
public class MyPagerAdapter extends FragmentPagerAdapter {
public static final int WEBVIEW_FRAGMENT_POSITION = 0;
public static final int SHOUTBOX_FRAGMENT_POSITION = 1;
private List<Fragment> fragments;
public MyPagerAdapter(FragmentManager fm) {
super(fm);
this.fragments = new ArrayList<Fragment>();
fragments.add(new WebViewFragment());
fragments.add(new Shoutbox());
}
public Fragment getItem(int position) {
return fragments.get(position);
}
public int getCount() {
return fragments.size();
}
}
Content.xml
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/myViewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#111" />
Any help would be greatly appreciated.

You can get the package libraries here
You content xml should be:
<packagename.JazzyViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/myViewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#111" />
You call the MainAdapter class to initialize the object and your various screens by:
JazzyViewPager mPager = (JazzyViewPager)findViewById(R.id.pager);
mPager.setAdapter(new MainAdapter());
Various transition effects are available like:
public enum TransitionEffect {
Standard,
Tablet,
CubeIn,
CubeOut,
Flip,
Stack,
ZoomIn,
ZoomOut,
RotateUp,
RotateDown,
Accordion
}
All these animations are placed in the JazzyViewPager class and you can call any one of the above mentioned animations by:
mPager.setTransitionEffect(TransitionEffect.*);
I hope the answer helps. I you still are unable to do it then i can post the code by which i have implemented the JazzyViewPager.

Related

How to serialize polymorphic list with element type names as xml element names in Jackson

I have a list of objects with common base class. I wish to serialize (and deserialize) this list so that each list element is serialized with its root element equal to the name of the type and not have the wrapping object around the element.
I tried using JsonTypeInfo with Id.Name and As.WRAPPER_OBJECT which produces an XML with proper element names but (obviously) with another layer of XML elements (from the list itself).
package zm.study.xmlserialize.jackson;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
public class JacksonListTest4 {
public static class L {
public List<A> as = new ArrayList<>();
}
#JsonTypeInfo(use = Id.NAME, include=As.WRAPPER_OBJECT)
#JsonSubTypes({
#JsonSubTypes.Type(value=B.class, name="b"),
#JsonSubTypes.Type(value=C.class, name="c"),
})
public static abstract class A {
}
public static class B extends A {
}
public static class C extends A {
}
#Test
public void test() throws Exception
{
L l = new L();
l.as.add(new B());
l.as.add(new C());
new XmlMapper().enable(SerializationFeature.INDENT_OUTPUT)
.writeValue(System.out, l);
}
}
I would like to get:
<L>
<as>
<b/>
<c/>
</as>
</L>
Instead I get:
<L>
<as>
<as>
<b/>
</as>
<as>
<c/>
</as>
</as>
</L>
If you know what you want it to look like you're better off writing an XSD and then using a tool like JAXB to create a serialization/deserialization Java object.

Automatically persist changes from two way data binding using Room?

Question
Two-Way DataBinding allows you to automatically populate UI components with data from an Object and then automatically update the Object as the user edits those UI components.
As the user edits UI components, is there a way to not only automatically update the Object in memory, but automatically update/persist the Object in a Room database?
I could manually listen to every UI field modification and manually save the Object to the Room Database. However, such a manual, brute force approach would negate the benefits of Two-Way DataBindings that I'm hoping to utilize.
Context
My application stores Items in an SQLite database using Android's Room Persistence Library. This is a simplified version of my Item:
#Entity
public class Item {
#PrimaryKey(autoGenerate = true)
private long id;
private String name;
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
The magic of ViewModel, LiveData, and Two-Way DataBindings allows my ItemEditorFragment to automatically populate the UI with data from the selected Item and to update that Item when the user edits the UI components:
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof ItemViewModelProvider) {
final ItemViewModelProvider itemViewModelProvider = (ItemViewModelProvider) context;
mViewModel = itemViewModelProvider.getItemViewModel();
} else {
throw new RuntimeException(context.toString()
+ " must implement ItemViewModelProvider");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final FragmentItemEditorBinding binding = DataBindingUtil.inflate(inflater, R.layout.fragment_item_editor, container, false);
binding.setViewModel(mViewModel);
binding.setLifecycleOwner(this);
final View view = binding.getRoot();
return view;
}
This is a simplified version of the layout being inflated:
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="viewModel"
type="com.lafave.ItemViewModel" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#={viewModel.selectedItem.name}"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
</layout>
One of the dirty hacks I've made work is: creating a new property, in the ViewModel (but it doesn't strictly have to be exactly there), without a backing field (in Java, this would probably equate to creating a getter and a setter, without a field):
var selectedItemName: String?
get() = selectedItem.value?.name
set(value) {
selectedItem.value?.let {
it.name = value
dao.update(it)
}
}
This is not an ideal solution, since it requires mirroring all of the properties in the class, but it works if you just want to get it over with. I'm awaiting a better solution!

How to call functions on the stage in JavaFX's controller file

I am using javafx along with fxml, so I use the controller for the real coding. I need to do a few operations on the stage, such as getting its x- or y-axis position. I have tried stage.getX() & stage.getY, but they don't work(the stage name is high-lited as the error). How do I use such functions in my controller? I tried doing this in my main file:
public int locationX = stage.getX();
and
public double locationX = stage.getX();
But it doesn't work, instead makes the whole program one big error.
So how do I get to do such functions in my controller file? Do I need to import something or do something like above in another way?
error: cannot find symbol
locationX = stage.getX();
symbol: variable stage
location: class FXMLController
I know that the "stage" is missing. But how to get the "stage" in my controller?
From your root Pane in the fxml file :
#FXML
Parent root
You can get the stage from it by:
Stage stage = (Stage) root.getScene().getWindow()
You have a reference to your stage, you can do what you want.
Sample Solution
You can initialize the stage in the controller using the technique from: Passing Parameters JavaFX FXML.
Here is a sample program which creates a utility window which tracks the x and y co-ordinates of the screen as you drag the utility window around. The contents of the utility window are rendered in an fxml defined pane.
StageTrackingSample.java
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.*;
import javafx.stage.*;
public class StageTrackingSample extends Application {
#Override public void start(final Stage stage) throws Exception {
final FXMLLoader loader = new FXMLLoader(
getClass().getResource(
"stagetracking.fxml"
)
);
final Parent root = (Parent) loader.load();
final StageTrackingController controller = loader.getController();
controller.initData(stage);
stage.initStyle(StageStyle.UTILITY);
stage.setResizable(false);
stage.setScene(new Scene(root));
stage.show();
}
public static void main(String[] args) { launch(args); }
}
StageTrackingController.java
import javafx.beans.binding.Bindings;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.stage.Stage;
public class StageTrackingController {
#FXML private Label stageX;
public void initialize() {}
public void initData(final Stage stage) {
stageX.textProperty().bind(
Bindings.format(
"(%1$.2f, %2$.2f)",
stage.xProperty(),
stage.yProperty()
)
);
}
}
stagetracking.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="30" minWidth="100" xmlns:fx="http://javafx.com/fxml" fx:controller="test.StageTrackingController">
<Label fx:id="stageX" layoutX="0" layoutY="0"/>
</AnchorPane>
Alternate Solutions
tarrsalah's answer of just getting the stage from an #FXML component is also a good way if you know that the root component of the controller has already been added to a scene which has already been added to a stage (which is often the case when something like a button event handler is fired).
Another way to do it is similar to tarrsalah's answer, but to use ChangeListeners on the scene property of an #FXML node and the window property of the changed scene. This allows you to track changes to the scene and stage in case the pane is moved to a new scene or stage. Most of the time you don't need to track those changes though as most panes are just added to a single scene which stays on one stage.
Answers to Additional Questions and Comments
Can I get a simpler answer?
tarrsalah already provided a simpler answer.
The only problem with a simpler answer in this case is that it might not provide enough context required for you to replicate the answer's solution and adapt it to your work.
I made my current answer as simple as I could, but, unfortunately, even the most basic JavaFX FXML application requires quite a bit code and markup to work.
I am a mere beginner in java
Don't use FXML when you are first starting to develop your initial Java and JavaFX applications. Instead, just stick with the standard Java API in your JavaFX code, for which there are many more tutorials as well as the excellent Ensemble Sample to refer to.
Make sure before beginning JavaFX, that you have completed all of the Java Tutorial Trails Covering the Basics. Only the basics of Java are required to start using JavaFX, you don't need to branch off into learning Java Enterprise Edition and can forget about Swing.
Consider using SceneBuilder and FXML for larger applications once you have written a few basic JavaFX applications, hand-coded some layouts according to the Java API and reached a level of comfort with the core technologies. At that time you will likely find that learning FXML is quite straightforward. FXML attributes and elements are just a reflection of the Java APIs.
please explain the other-than-usual bits of your code
I can't really do that as I don't know what is unusual for you.
If there are particular parts of the code that you cannot understand through your own knowledge or research, create a new StackOverflow question for each difficult concept.
Well, the simplest answer to that...
In your Main class create an instance (an object) of your Controller class:
FXMLLoader loader = new FXMLLoader(getClass().getResource("Example.fxml"));
MyController controller = loader.getController();
controller.setStage(this.stage);
In your Controller class you should put a method of "extraction" (a setter):
private Stage primaryStage;
public void setStage(Stage stage) {
this.primaryStage = stage;
}
And then you can add a fullscreen button ;)
#FXML
private Button btnFullScreen = new Button();
public void setFullscreen(ActionEvent event){
if(primaryStage.isFullScreen()){
primaryStage.setFullScreen(false);
} else {
primaryStage.setFullScreen(true);
}
}
This thread is old, but I discovered something pertinent to it quite by accident. What I thought was a coding error that shouldn't have worked, yet it did. In the controller class, simply declaring the following member variable:
#FXML private Stage stage;
gave me access to the stage in the controller, much like I have access to a widget in the fxml document. I have not found any documentation that this is the case, but I'll admit I am noob to JavaFX (although an old hand at Swing). But it seems to work. Maybe it's dangerous to count on it though?
With *.FXML files and Controllers and not with Main or Events , use this :
#FXML private Stage stage;
stage = (Stage) elemen.getScene().getWindow();
element, can be any control or element in you FXML, in my case is an AnchorPane:
#FXML private AnchorPane element;
The best approach is to create a new controller and pass the stage via the constructor (don't use fx:controller on FXML file), otherwise the stage will be null when initialize() is invoked (At that moment of time, when load() invokes initialize(), no stage is attached to the scene, hence the scene's stage is null).
public class AppEntryPoint extends Application
{
private FXMLLoader loader;
#Override
public void init() throws Exception
{
loader = new FXMLLoader(getClass().getResource("path-to-fxml-file"));
}
#Override
public void start(Stage initStage) throws Exception
{
MyController controller = new MyController(initStage);
loader.setController(controller);
Scene scene = loader.load();
initStage.setScene(scene);
initStage.show();
}
public static void main(String[] args)
{
launch(args);
}
}
public class MyController
{
private Stage stage;
#FXML private URL location;
#FXML private ResourceBundle resources;
public MyController(Stage stage)
{
this.stage = stage;
}
#FXML
private void initialize()
{
// You have access to the stage right here
}
}

Icefaces ace:dataTable lazy loading

Is there anybody who have a little example of a lazy loading with ace:dataTable?..
I can't understand how to implement the load method of the class LazyDataModel.. and how to fetch data from a Database through this method..
thanks!
ace:dataTable has already a "built in" lazy loading mechanism in ICEFaces
(at least for release 3.x and up).
No need to extend an AbstractList for this anymore.
All you need to do is add the lazy="true" to your tag, and make sure the "value" attribute points to a class that extends LazyDataModel... you just need to implement the abstract
method there that accepts start page, page size, sorting & filtering arguments.
Also don't forget to use pagination and determine the size of the page ("rows" attribute).
Check: ICEFaces docs Ver. 3 ace:dataTable
Here's working sample
myDataTableLazy.xhtml
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:ace="http://www.icefaces.org/icefaces/components"
xmlns:ice="http://www.icesoft.com/icefaces/component"
xmlns:icecore="http://www.icefaces.org/icefaces/core">
<h:head>
<title>DataTable</title>
</h:head>
<h:body>
<h:form>
<ace:dataTable id="carTable"
value="#{myDataTableLazy.lazyModel}"
var="car"
rows="5"
paginator="true"
lazy="true" >
<ace:column id="exp" rendered="false">
<ace:expansionToggler />
</ace:column>
<ace:column headerText="Id">
<ice:outputText value="#{car.id}" />
</ace:column>
<ace:column headerText="Name">
<ice:outputText value="#{car.name}" />
</ace:column>
</ace:dataTable>
<h:commandButton id="invio" value="Invio" actionListener="#{myDataTableLazy.cicla}" >
</h:commandButton>
</h:form>
MyDataTableLazy
package my;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ActionEvent;
import org.icefaces.ace.model.table.LazyDataModel;
import org.icefaces.samples.showcase.example.ace.dataTable.DataTableLazyLoading;
import org.icefaces.samples.showcase.metadata.context.ComponentExampleImpl;
#ManagedBean(name="myDataTableLazy")
#SessionScoped
public class MyDataTableLazy implements Serializable {
private LazyDataModel<Car> lazyModel;
#PostConstruct
public void init() {
lazyModel = new LazyCarDataModel();
}
public LazyDataModel<Car> getLazyModel() {
return lazyModel;
}
public void setLazyModel(LazyDataModel<Car> lazyModel) {
this.lazyModel = lazyModel;
}
public void cicla(ActionEvent e) {
List<Car> lista = (List<Car>) lazyModel.getWrappedData();
for (Car car : lista) {
System.out.println( car.getName() );
}
}
}
LazyCarDataModel
package my;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.icefaces.ace.model.table.LazyDataModel;
import org.icefaces.ace.model.table.SortCriteria;
public class LazyCarDataModel extends LazyDataModel<Car> {
List<Car> carList;
public LazyCarDataModel(){
carList = new ArrayList<Car>();
carList.add(new Car(1, "FiatLazy"));
carList.add(new Car(2, "FerrariLazy"));
carList.add(new Car(3, "PorscheLazy"));
carList.add(new Car(4, "MaseratiLazy"));
carList.add(new Car(5, "MercedesLazy"));
carList.add(new Car(6, "BMWLazy"));
carList.add(new Car(7, "ToyotaLazy"));
carList.add(new Car(8, "FordLazy"));
carList.add(new Car(9, "Alfa RomeoLazy"));
carList.add(new Car(10, "SuzukiLazy"));
carList.add(new Car(11, "RenaultLazy"));
setRowCount(carList.size());
}
#Override
public List<Car> load(int first, int pageSize, SortCriteria[] arg2, Map<String, String> arg3) {
ArrayList list = new ArrayList<Car>();
int initial = first;
for (int i = initial; i < initial + pageSize && i < carList.size(); i++) {
list.add(carList.get(i));
}
return list;
}
}
ICEFaces ice/ace:DataTable underneath works with native Java Collections. Datatable accesses elements from your collection simply by invoking get(idx) method on your collection.
I suggest you should look into implementing lazy-loading/pagination on the lower level, like implementing your own java.util.AbstractList.
Start by implementing its abstract get() method and debugging, to understand how icefaces datatable works, alternatively you can check out ice/ace:dataTable ice/ace:dataPaginator sources.
Since IceFaces Ace is a copy/fork of PrimeFaces 2, PrimeFaces docs and samples may help. primefaces.org/showcase-labs/ui/datatableLazy.jsf
Pheraps it's quite off-topic, but to build the showcase examples:
go to http://www.icesoft.org/java/downloads/icefaces-downloads.jsf
you can select ICEfaces 4.x ICEfaces 3.x ICEfaces 1.x tab
download the ICEfaces-x.x.0-bin.zip file (you do the registration)
unzip and go to the folder you want compile, for example, in the command shell, go to
...\ICEfaces-3.3.0-bin.zip\ICEfaces-3.3.0-bin\icefaces\samples\showcase\showcase
launch the command (you must have maven):
mvn package
the you'll find showcase.war in
\ICEfaces-3.3.0-bin\ICEfaces-3.3.0-bin\icefaces\samples\showcase\showcase\target

Simplest wat to integrate Unity with MVC3

I have a console app with config:
<?xml version="1.0" encoding="utf-8" ?> <configuration>
<configSections>
<section name="unity" type=
"Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,
Microsoft.Practices.Unity.Configuration" />
</configSections>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<assembly name="UnityDi.Contracts" />
<assembly name="UnityDi.Domain" />
<assembly name="UnityDi.Services" />
<assembly name="UnityDi.Repositories" />
<namespace name="UnityDi.Contracts" />
<namespace name="UnityDi.Domain" />
<namespace name="UnityDi.Services" />
<namespace name="UnityDi.Repositories" />
<container>
<register type="IUser" mapTo="User"></register>
<register type="IUserService" mapTo="UserService"></register>
<register type="IUserRepository" mapTo="UserRepository"></register>
</container>
</unity>
</configuration>
and Program.cs
namespace UnityDi.Console
{
using System;
using Contracts;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
public static class Program
{
private static readonly IUnityContainer Container =
new UnityContainer().LoadConfiguration();
public static void Main()
{
var dummyUserOne = GetUserReference();
dummyUserOne.UserId = 1;
dummyUserOne.FullName = "Bilbo Baggins";
var dummyUserTwo = GetUserReference();
dummyUserTwo.UserId = 2;
dummyUserTwo.FullName = "Frodo Baggins";
var userService = GetUserServiceReference();
userService.Add(dummyUserOne);
userService.Add(dummyUserTwo);
var users = userService.GetAllUsers();
foreach (var user in users)
{
Console.WriteLine(user.FullName);
}
Console.ReadLine();
}
private static IUser GetUserReference()
{
return Container.Resolve<IUser>();
}
private static IUserService GetUserServiceReference()
{
return Container.Resolve<IUserService>();
}
}
}
That works really well.
I've been doing a lot of searching around and find that solutions published integrating Unity with MVC3 seem to be very verbose in their approach.
Within the context of the code above (and with a requirement to wire up Entity Framework code first), what's the SIMPLEST way for me to integrate Unity with MVC3 and work with my data like above?
I want to use the exact same approach to creating my objects in MVC as above.
Thanks!
Richard
P.s. The closest I found was Unity.Mvc but I can't get it to work like above. I'm probably being stupid though. This is new to me.
EDIT: Working with the proposed answer.
In Web.config for the MVC app (with Unity.Mvc package added)
[snip]
<container>
<register type="IUser" mapTo="User"></register>
<register type="IUserService" mapTo="UserService"></register>
<register type="IUserRepository" mapTo="UserRepository">
<lifetime type="HierarchicalLifetimeManager" />
</register>
</container>
Then in Bootstrapper.cs
namespace Unity.Mvc.Resources
{
using System.Web.Mvc;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using Unity.Mvc3;
public static class Bootstrapper
{
public static void Initialise()
{
var container = BuildUnityContainer();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer().LoadConfiguration();
container.RegisterControllers();
return container;
}
}
}
Then in the controller (bit of an a-ha moment when I realised the Interface can be any Unity knows about, including it's own):
private readonly IUnityContainer container;
public HomeController(IUnityContainer container)
{
this.container = container;
}
public ActionResult Index()
{
var dummyUserOne = GetUserReference();
dummyUserOne.UserId = 1;
dummyUserOne.FullName = "Bilbo Baggins";
var dummyUserTwo = GetUserReference();
dummyUserTwo.UserId = 2;
dummyUserTwo.FullName = "Frodo Baggins";
var userService = GetUserServiceReference();
userService.Add(dummyUserOne);
userService.Add(dummyUserTwo);
var users = userService.GetAllUsers();
return View(users);
}
private IUser GetUserReference()
{
return container.Resolve<IUser>();
}
private IUserService GetUserServiceReference()
{
return container.Resolve<IUserService>();
}
And again, it works :)
That just leaves the Entity Framework aspect. Need to get DbContext wired up to work with my Domain objects without introducing additional dependencies... Any pointers? Really, very much appreciated.
Install the Unity.Mvc3 nuget package.
go to the bootstrapper code and add your mapping (get it working like that then fiddle around with doing it in a config file if you so desire)
The bootstrapper will 'hook' into mvc to let it know for controller resolution to use unity.
ex:
container.RegisterType<ICustomerRepository, CustomerRepository>();
Any constructors for controllers will look for any interfaces unity needs to do mappings on. If it has to inject IService, it will (As long as it knows about it).
If it has to repeat this process throughout the object grab (IService required IRepository, etc on down the graph) as long as unity knows about it, it will wire everything up.
For the additional question on the Entity Framework, I use an IContext class. In here I define IDbSet Customers. This is similar to this implementation:
http://leomburke.wordpress.com/category/entity-framework/

Resources