I'm using processing's liquidfun library to simulate particle interactions, such as changing color on collision, but I can't find a contactlistener for individual liquid particles. There's a built in contactlistener for JBox2D objects, but it doesn't apply to the particles themselves.
public void initscene() {
...
world.setContactListener(new MyContactListener());
}
class MyContactListener implements ContactListener {
#Override
public void beginContact(Contact contact) {
println(contact.getFixtureA());
println(contact.getFixtureB());
}
#Override
public void endContact(Contact contact) {
}
#Override
public void preSolve(Contact contact, Manifold oldManifold) {
}
#Override
public void postSolve(Contact contact, ContactImpulse impulse) {
}
}
This only outputs anything when JBox2D objects come in contact, rather than all interactions, including between LiquidFun particles.
Related
my viewpager is different (with multy xml and java file.means page1 java and xml file,page2 java and xml file,page3 java and xml files are seprate).
and want to sate cubeout effect in my viewpager.
**this is my coad **
public class MercuryActivity extends FragmentActivity implements OnPageListener {
List fragments = new Vector();
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.fragments.add(Fragment.instantiate(this, Page1Fragment.class.getName()));
this.fragments.add(Fragment.instantiate(this, Page2Fragment.class.getName()));
this.fragments.add(Fragment.instantiate(this, Page3Fragment.class.getName()));
this.fragments.add(Fragment.instantiate(this, Page4Fragment.class.getName()));
this.mPagerAdapter = new PagerAdapter(super.getSupportFragmentManager(), this.fragments);
this.mPager = (ViewPager) super.findViewById(R.id.pager);
this.mPager.setAdapter(this.mPagerAdapter);
}
public void onPage1(String s) {
((Page2Fragment) this.fragments.get(1)).getView();
((Page3Fragment) this.fragments.get(2)).getView();
((Page4Fragment) this.fragments.get(3)).getView();
}
public void onBackPressed() {
new Builder(this).setIcon(17301543).setTitle("Exit").setMessage("Are you sure you want to exit?").setPositiveButton("Yes", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
MercuryActivity.this.moveTaskToBack(true);
MercuryActivity.this.finish();
}
}).setNegativeButton("No", null).show();
}
}
and this is my page adapter
public class PagerAdapter extends FragmentPagerAdapter {
private List fragments;
public PagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
public Fragment getItem(int position) {
return (Fragment) this.fragments.get(position);
}
public int getCount() {
return this.fragments.size();
}
}
I'm investigating the best way to write a rich text editor in JavaFX - don't mention the HTMLEditor to me: we've spent literally months hacking at it and I could write reams about why it isn't suitable for our purposes! Choice at the moment is to extend AnchorPane and do all of the layout, navigation etc. from scratch or to extend TextInputArea, which looks as though it would help. Anyone have their own implementation of that or would like to propose a minimal implementation?
FWIW here's a scrap from me:
public class TryPain3 extends TextInputControl {
private AnchorPane rootNode = new AnchorPane();
public TryPain3() {
super(new Content() {
private String text = "";
#Override
public String get(int i, int i1) {
return text.substring(i, i1);
}
#Override
public void insert(int i, String string, boolean bln) {
}
#Override
public void delete(int i, int i1, boolean bln) {
}
#Override
public int length() {
return text.length();
}
#Override
public String get() {
return text;
}
#Override
public void addListener(ChangeListener<? super String> cl) {
}
#Override
public void removeListener(ChangeListener<? super String> cl) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public String getValue() {
return text;
}
#Override
public void addListener(InvalidationListener il) {
}
#Override
public void removeListener(InvalidationListener il) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});
setEditable(true);
Text text1 = new Text("fred was here");
text1.setFont(Font.font("Tahoma", FontWeight.NORMAL, 18));
text1.setTextAlignment(TextAlignment.LEFT);
text1.setFontSmoothingType(FontSmoothingType.LCD);
rootNode.getChildren().add(text1);
setSkin(new TP3Skin(this, rootNode));
}
class TP3Skin implements Skin<TryPain3> {
TryPain3 tp;
Node root;
public TP3Skin(TryPain3 tp, Node root) {
this.tp = tp;
this.root = root;
}
#Override
public TryPain3 getSkinnable() {
return tp;
}
#Override
public Node getNode() {
return root;
}
#Override
public void dispose() {
tp = null;
rootNode = null;
}
}
}
It looks as though the skin is not optional.
Questions I'd like to find out are things like:
how is the UI supposed to be drawn - I'm quite happy to code it from scratch but how to get benefit of calls to forward() as an example
should the UI creation be done in the Skin?
whether the base class deals with things like where to put the cursor if you click on a bit of text
I'm sure other questions will arise from this.
You may want to try next JavaFX 8.0 control TextFlow, which allows aggregation of various text styles. See examples here: https://wikis.oracle.com/display/OpenJDK/Rich+Text+API+Samples
JavaFX 8 is part of JDK8. So you can download developers build here http://jdk8.java.net/download.html and it will include JavaFX and new TextFlow control.
This is a wierd problem.
This will be a terrible question because I have little to no information.
About two days ago I had the ViewPagerAdapter working just fine. I could swipe and it would switch between views as defined by the adapter.
However, all of a sudden (not by itself, I'm sure I did something) the TitlePagerIndicator doesn't snap to the headings and doesn't display any content. By not snapping I mean that if I drag to the left, the title will sit at 3/4 of the screen instead of snapping to the side and displaying the next page (screenshot below).
I have debugged and instantiate item is called and a proper view is returned.
However, when I open the app I'm getting a lot of warnings like these:
VFY: unable to resolve virtual method 3015: Landroid/widget/LinearLayout;.getAlpha ()F
VFY: unable to resolve direct method 3011: Landroid/widget/LinearLayout;. (Landroid/content/Context;Landroid/util/AttributeSet;I)V
VFY: unable to resolve virtual method 2965: Landroid/widget/FrameLayout;.setAlpha (F)V
I'm assuming this is a problem with my imports, but everything compiles just fine, I have the ViewPagerIndicator as a library project, as well as Sherlock.
Here's my adapter code:
public class ViewPagerAdapter extends PagerAdapter implements TitleProvider {
private static String[] titles = new String[] {
"My Klinks",
"Received Klinks"
};
private final Context context;
public ViewPagerAdapter(Context context) {
this.context = context;
}
public String getTitle(int position) {
return titles[position];
}
#Override
public int getCount() {
return titles.length;
}
#Override
public Object instantiateItem(View pager, int position) {
TextView t = new TextView(context);
t.setText("WheeeE");
return t;
}
#Override
public void destroyItem(View pager, int position, Object view) {
((ViewPager) pager).removeView((TextView) view);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void finishUpdate(View view) {
}
#Override
public void restoreState(Parcelable p, ClassLoader c) {
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void startUpdate(View view) {
}
}
And here is my activity code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.main );
// set up the slidey tabs
ViewPagerAdapter adapter = new ViewPagerAdapter( this );
ViewPager pager = (ViewPager)findViewById( R.id.viewpager );
TitlePageIndicator indicator = (TitlePageIndicator)findViewById( R.id.indicator );
pager.setAdapter( adapter );
indicator.setViewPager( pager );
// set up the action bar
final ActionBar ab = getSupportActionBar();
ab.setBackgroundDrawable(getResources().getDrawable(R.drawable.ad_action_bar_gradient_bak));
}
If someone else gets the same problem:
In instantiateView: don't forget to attach your new View to the ViewPager:
#Override
public Object instantiateItem(View pager, int position) {
TextView t = new TextView(context);
t.setText("WheeeE");
((ViewPager)pager).addView(t);
return t;
}
The current version of instantiateItem gets a ViewGroup instead of a View, the solution should be the same.
Well after a couple days of banging my head against a wall I've come to the conclusion that my ViewPagerAdapter was the problem.
I simply created a dynamic fragment and created a subclass of FragmentPagerAdapter instead and now it works just fine...
I've converted my AsyncTask to an AsyncTaskLoader (mostly to deal with configuration changes). I have a TextView I am using as a progress status and was using onProgressUpdate in the AsyncTask to update it. It doesn't look like AsyncTaskLoader has an equivalent, so during loadInBackground (in the AsyncTaskLoader) I'm using this:
getActivity().runOnUiThread(new Runnable() {
public void run() {
((TextView)getActivity().findViewById(R.id.status)).setText("Updating...");
}
});
I am using this in a Fragment, which is why I'm using getActivity(). This work pretty well, except when a configuration change happens, like changing the screen orientation. My AsyncTaskLoader keeps running (which is why I'm using an AsyncTaskLoader), but the runOnUiThread seems to get skipped.
Not sure why it's being skipped or if this is the best way to update the UI from an AsyncTaskLoader.
UPDATE:
I ended up reverting back to an AsyncTask as it seems better suited for UI updates. Wish they could merge what works with an AsyncTask with an AsyncTaskLoader.
It's actually possible. You essentially need to subclass the AsyncTaskloader and implement a publishMessage() method, which will use a Handler to deliver the progress message to any class that implements the ProgressListener (or whatever you want to call it) interface.
Download this for an example: http://www.2shared.com/file/VW68yhZ1/SampleTaskProgressDialogFragme.html (message me if it goes offline) - this was based of http://habrahabr.ru/post/131560/
Emm... you shouldn't be doing this.
because how an anonymous class access parent class Method or Field is by storing an invisible reference to the parent class.
for example you have a Activity:
public class MyActivity
extends Activity
{
public void someFunction() { /* do some work over here */ }
public void someOtherFunction() {
Runnable r = new Runnable() {
#Override
public void run() {
while (true)
someFunction();
}
};
new Thread(r).start(); // use it, for example here just make a thread to run it.
}
}
the compiler will actually generate something like this:
private static class AnonymousRunnable {
private MyActivity parent;
public AnonymousRunnable(MyActivity parent) {
this.parent = parent;
}
#Override
public void run() {
while (true)
parent.someFunction();
}
}
So, when your parent Activity destroys (due to configuration change, for example), and your anonymous class still exists, the whole activity cannot be gc-ed. (because someone still hold a reference.)
THAT BECOMES A MEMORY LEAK AND MAKE YOUR APP GO LIMBO!!!
If it was me, I would implement the "onProgressUpdate()" for loaders like this:
public class MyLoader extends AsyncTaskLoader<Something> {
private Observable mObservable = new Observable();
synchronized void addObserver(Observer observer) {
mObservable.addObserver(observer);
}
synchronized void deleteObserver(Observer observer) {
mObservable.deleteObserver(observer);
}
#Override
public void loadInBackground(CancellationSignal signal)
{
for (int i = 0;i < 100;++i)
mObservable.notifyObservers(new Integer(i));
}
}
And in your Activity class
public class MyActivity extends Activity {
private Observer mObserver = new Observer() {
#Override
public void update(Observable observable, Object data) {
final Integer progress = (Integer) data;
mTextView.post(new Runnable() {
mTextView.setText(data.toString()); // update your progress....
});
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreated(savedInstanceState);
MyLoader loader = (MyLoader) getLoaderManager().initLoader(0, null, this);
loader.addObserver(mObserver);
}
#Override
public void onDestroy() {
MyLoader loader = (MyLoader) getLoaderManager().getLoader(0);
if (loader != null)
loader.deleteObserver(mObserver);
super.onDestroy();
}
}
remember to deleteObserver() during onDestroy() is important, this way the loader don't hold a reference to your activity forever. (the loader will probably be held alive during your Application lifecycle...)
Answering my own question, but from what I can tell, AsyncTaskLoader isn't the best to use if you need to update the UI.
In the class in which you implement LoaderManager.LoaderCallback (presumably your Activity), there is an onLoadFinished() method which you must override. This is what is returned when the AsyncTaskLoader has finished loading.
The best method is to use LiveData, 100% Working
Step 1: Add lifecycle dependency or use androidx artifacts as yes during project creation
implementation "androidx.lifecycle:lifecycle-livedata:2.1.0"
Step 2: Create the loader class as follow, in loader create in public method to set the livedata that can be observed from activity or fragment. see the setLiveCount method in my loader class.
package com.androidcodeshop.asynctaskloaderdemo;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.MutableLiveData;
import androidx.loader.content.AsyncTaskLoader;
import java.util.ArrayList;
public class ContactLoader extends AsyncTaskLoader<ArrayList<String>> {
private MutableLiveData<Integer> countLive = new MutableLiveData<>();
synchronized public void setLiveCount(MutableLiveData<Integer> observer) {
countLive = (observer);
}
public ContactLoader(#NonNull Context context) {
super(context);
}
#Nullable
#Override
public ArrayList<String> loadInBackground() {
return loadNamesFromDB();
}
private ArrayList<String> loadNamesFromDB() {
ArrayList<String> names = new ArrayList<>();
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
names.add("Name" + i);
countLive.postValue(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return names;
}
#Override
protected void onStartLoading() {
super.onStartLoading();
forceLoad(); // forcing the loading operation everytime it starts loading
}
}
Step 3: Set the live data from activity and observe the change as follows
package com.androidcodeshop.asynctaskloaderdemo;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.MutableLiveData;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.Loader;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements
LoaderManager.LoaderCallbacks<ArrayList> {
private ContactAdapter mAdapter;
private ArrayList<String> mNames;
private MutableLiveData<Integer> countLiveData;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNames = new ArrayList<>();
mAdapter = new ContactAdapter(this, mNames);
RecyclerView mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mAdapter);
countLiveData = new MutableLiveData<>();
countLiveData.observe(this, new androidx.lifecycle.Observer<Integer>() {
#Override
public void onChanged(Integer integer) {
Log.d(TAG, "onChanged: " + integer);
Toast.makeText(MainActivity.this, "" +
integer,Toast.LENGTH_SHORT).show();
}
});
// initialize the loader in onCreate of activity
getSupportLoaderManager().initLoader(0, null, this);
// it's deprecated the best way is to use viewmodel and livedata while loading data
}
#NonNull
#Override
public Loader onCreateLoader(int id, #Nullable Bundle args) {
ContactLoader loader = new ContactLoader(this);
loader.setLiveCount(countLiveData);
return loader;
}
#Override
public void onLoadFinished(#NonNull Loader<ArrayList> load, ArrayList data) {
mNames.clear();
mNames.addAll(data);
mAdapter.notifyDataSetChanged();
}
#Override
public void onLoaderReset(#NonNull Loader loader) {
mNames.clear();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
Hope this will help you :) happy coding
I have an enum, say Fruits { Apple, Banana, Cherry }. I want to write a event subsystem for my application so that I can have the following pattern :
class AppleListener implements HasFruitPriceChangeListener<Apple> {
onFruitPriceChange(int newPrice) {
// do stuff
}
}
and a single listener, that can delegate tasks in the following format:
class FruitPriceListener {
public void onPriceChange(EnumMap<Fruits, Integer> pricePoints) {
// for each fruit, throw the event as
// FruitPriceChange.fire(Apple, newPrice);
}
}
Is there a way to do it in the above manner ? I would probably like to use ValueChangeEvent, but creating another 1 event and handler is also fine too. What I do not want to do is have event/class definitions for each item, like AppleFruitPriceChangeEvent, and so on.
You can use the EventBus for this things, which google suggested ( http://www.youtube.com/watch?v=PDuhR18-EdM ) Here how to use it.
Your globl Eventbus
public static SimpleEventBus bus = new SimpleEventBus();
Your change event:
import com.google.gwt.event.shared.GwtEvent;
import eyeweb.client.gwtMessages.JSPollingEntry;
public class EventModified extends GwtEvent<EventModifiedHandler> {
public final static Type<EventModifiedHandler> TYPE = new Type<EventModifiedHandler>();
private final Fruits fruits;
public final JSPollingEntry getPollingMessage(){
return fruits;
}
public EventModified(Fruits fruits) {
this.fruits = fruits;
}
#Override
public com.google.gwt.event.shared.GwtEvent.Type<EventModifiedHandler> getAssociatedType() {
return TYPE;
}
#Override
protected void dispatch(EventModifiedHandler handler) {
handler.onUpdateRecivde(this);
}
}
the handler for the event
package eyeweb.client.eventbus;
import com.google.gwt.event.shared.EventHandler;
public interface EventModifiedHandler extends EventHandler {
public void onUpdateRecivde(EventModified handler);
}
The event when something changes
EventBus.bus.fireEvent(new EventModified(fruite));
and the handler which gets the event
EventBus.bus.addHandler(EventModified .TYPE, new EventModifiedHandler() {
#Override
public void onMessageSend(EventSendData e) {
//... do stuff }
});
Well that sould be all ;)
Regards,
Stefan
So the solution I came up with was:
Create the enum, and associate a GwtEvent.Type with them:
enum Fruits {
Apple, Banana, Cherry;
public GwtEvent.Type getGwtEventType() {
return new GwtEvent.Type();
}
}
Create a new event.
class FruitPriceChangeEvent extends GwtEvent<?> {
private final Fruit fruit;
FruitPriceChangeEvent(Fruit fruitEnum) {
this.fruit = fruitEnum;
}
#Override
public GwtEvent.Type<?> getAssociatedType() {
return fruit.getGwtEventType();
}
// ... other stuff...
}
And then pass it through the whole event handler loop as #Stefan has mentioned. The beauty/hack of this approach is that the SimpleEventBus maintains a HashMap<GwtEvent.Type, List<HasHandlers>> from which to get the events, and everytime you create a new GwtEvent.Type it generates a unique hashcode (check the implementation for more details).
References:
http://grepcode.com/file/repo1.maven.org/maven2/com.google.gwt/gwt-servlet/2.1.1-rc1/com/google/gwt/event/shared/GwtEvent.java?av=f
http://grepcode.com/file/repo1.maven.org/maven2/com.google.gwt/gwt-servlet/2.1.1-rc1/com/google/gwt/event/shared/SimpleEventBus.java?av=f