我需要将UI元素引用传递给非活动类,无论该元素是什么类型。然后将 onTouchEvent 附加到该非活动类中的该元素。
我该怎么办?我在互联网上搜索过但没有找到任何帮助。
答案 0 :(得分:1)
您沿构造函数或方法调用传递上下文。 例如:
MyNonActivityClass myObject = new MyNonActivityClass(getActivity());
import android.content.Context;
import your.package.name.R; // notice the R you should add your package
// infront of R it should be something like
// com.example.myapp.R
public class MyNonActivityClass{
private Context context;
public MyNonActivityClass(Context c){
if(context instanceof MyActivityClass){
this.context=c;
}
/** you can do multi if else statements for multi activity classes **/
}
private void someMethodToHandleUi(){
View v = ((MyActivityClass)context).findViewById(R.id.myView);
v.setOnTouchListener(new OnTouchListener(){
// rest of your code
});
}
}
答案 1 :(得分:0)
我找到了不需要上下文的解决方案或条件,我需要做的就是将元素引用作为对象传递给class,而不是使用WeakReference将引用传递给View。
以下是代码:
public class NonActivityClass{
private WeakReference<Object> target;
public NonActivityClass(Object target){
this.target = new WeakReference<Object>(target);
}
@Nullable
public Object getTarget() {
return target == null ? null : target.get();
}
public void doSomethingWithUIElement(){
View view = (View) getTarget();
view.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
}
}