5

我正在将 AspectJ 与 Android 一起使用,并且我成功地捕获View.setOnClickListener()了对这方面的调用:

public aspect Test {

    pointcut callPointcut(View view, OnClickListener listener) : call(void View.setOnClickListener(OnClickListener)) && target(view) && args(listener);

    @SuppressAjWarnings // Exported advice
    before(View view, OnClickListener listener) : callPointcut(view, listener)
    {
        Log.d("AspectJ", "Attempt to set onClick listener on view " + Integer.toHexString(view.getId()));
        Log.d("AspectJ", "Aspect has executed.");
        Log.d("AspectJ", listener.toString());
    }
}

不幸的是,这不会捕获android:onClick在布局 XML 中设置的侦听器。有没有办法捕捉到这一点?

4

3 回答 3

1

你不能那样做。

如果我理解正确,您在 Views 上收听 setOnClickListener() 的调用。

当您在 xml 中设置 onclick 属性时,它永远不会被调用。侦听器在创建视图时设置 - 直接。setOnClickListener() 永远不会被调用。

唯一的解决方案是手动检查您的所有视图 - 这不是推荐的,也可能不是您想要的。

于 2012-09-18T13:17:44.837 回答
1

I'm not 100% sure if this will work, but why not modify the View class to have an mOnClickListener attribute. Then when the OnClickListener is about to be set in the custom View class, set the attribute to "new OnClickListener(){ ... }" then call setOnClickListener with the attribute. You would then add a public method called getOnClickListener(), which you could call on your custom View object to return said listener.

This may be a roundabout / tedious way, because you would also need to include not only your custom View class, but every subclass of View that you plan on using in your XML and change their superclasses to use your custom View, not Android's. Then, you would need to change your XML elements to reflect that, i.e. com.yourpackage.Button, etc.

于 2012-09-21T16:51:25.263 回答
-5

您可以使用,

 <TextView
            android:id="@+id/display_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="3dp"
            android:onClick="testclick"
            android:textSize="16sp"
            android:textStyle="bold" >

在您的活动中添加以下 API,

public void textclick(View v){

//TODO :anything you want 
}
于 2012-09-17T04:55:33.780 回答