我有一个向地图添加精确点的项目。对于地图,我们使用GestureImageView使其可滚动,并使用按钮ImageButton。
但是发生了以下问题:每当我们移动地图时,都必须确保精确点保持在原位。
问题是我们从GestureImageView内部的另一个线程调用ImageButton的转换函数,并且不允许您调用该视图。
E/AndroidRuntime﹕ FATAL EXCEPTION: GestureImageViewAnimator
Process: nl.example.android, PID: 17024
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6915)
at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:1089)
at android.view.ViewGroup.invalidateChildFast(ViewGroup.java:4639)
at android.view.View.invalidateViewProperty(View.java:11748)
at android.view.View.setTranslationY(View.java:11102)
at nl.example.android.GestureImageView.setPosition(GestureImageView.java:455)
at nl.example.android.GestureImageViewTouchListener.handleDrag(GestureImageViewTouchListener.java:449)
at nl.example.android.GestureImageViewTouchListener$1.onMove(GestureImageViewTouchListener.java:122)
at nl.example.android.FlingAnimation.update(FlingAnimation.java:49)
at nl.example.android.Animator.run(Animator.java:45)
我现在尝试的是:活动上下文的类
public class MyActivity extends Activity {
private static Activity activity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = this;
}
}
GestureImageView中的代码:
final float transX = x;
MyActivity myActivity = new MyActivity();
myActivity.runOnUiThread(new Runnable() {
public void run() {
setTranslationY(transX);
}
});
MainActivity中的代码:
MyActivity myActivity = new MyActivity();
Runnable runnable = new Runnable() {
@Override
public void run() {
pin1.setTranslationY(3);
synchronized(this){
this.notify();
}
}
};
synchronized(runnable) {
myActivity.runOnUiThread(runnable);
runnable.wait() ; // unlocks myRunable while waiting
}
最佳答案
在文件GestureImageView中,行455尝试一下:
activity.runOnUiThread(new Runnable(){
public void run(){
setTranslationZ(x);
}
});
您不能从其他线程调用视图函数。您必须在main上调用它。如果要等待结束执行runOnUiThread,请使用以下命令:
Runnable r = new Runnable(){public void run(){
setTranslationZ(...);
synchronized(this){
this.notify();
}
}};
synchronized( myRunnable ) {
activity.runOnUiThread(myRunnable);
myRunnable.wait() ; // unlocks myRunable while waiting
}
为不知道如何使用runOnUiThread的人进行编辑:
class GestureImageView extends View{
private long thread;
public GestureImageView(Context c){
super(c);
thread=Thread.currentThread().getId();
}
public void setTranslationZ(final int n){
if(thread==Thread.currentThread().getId()){ //this is UI thread
super.setTranslationZ(n);
} else {
MainActivity.instance.runOnUiThread(new Runnable(){
public void run() {
setTranslationZ(n);
}
});
}
}
}
public class MainActivity extends Activity
{
public static Activity instance;
public MainActivity(){
instance=this;
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
}
关于java - ImageButton在GestureImageView上的固定位置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29344929/