如何将任何 android 元素传递给非 activity class 并在 class 中为该元素设置 onTouch?
How to pass any android element to non-activity class and set onTouch for that element in that class?
我需要将 UI 元素引用传递给非 activity class,无论该元素是什么类型。然后将 onTouchEvent 附加到非 activity class 内的那个元素。
我该怎么做?我在网上搜索过,但没有找到任何有用的信息。
您通过构造函数或方法调用传递上下文。
示例:
MyNonActivityClass myObject = new MyNonActivityClass(getActivity());
MyNonActivityClass
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
});
}
}
我找到了不需要上下文或 if 条件的解决方案,我需要做的就是将元素引用作为对象传递给 class,而不是使用 WeakReference 传递对视图的引用。
代码如下:
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;
}
});
}
}
我需要将 UI 元素引用传递给非 activity class,无论该元素是什么类型。然后将 onTouchEvent 附加到非 activity class 内的那个元素。
我该怎么做?我在网上搜索过,但没有找到任何有用的信息。
您通过构造函数或方法调用传递上下文。 示例:
MyNonActivityClass myObject = new MyNonActivityClass(getActivity());
MyNonActivityClass
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
});
}
}
我找到了不需要上下文或 if 条件的解决方案,我需要做的就是将元素引用作为对象传递给 class,而不是使用 WeakReference 传递对视图的引用。
代码如下:
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;
}
});
}
}