这个问题难倒了我。

我需要从自定义布局类中调用一个活动方法。这样做的问题是,我不知道如何从布局内访问活动。

ProfileView

public class ProfileView extends LinearLayout
{
    TextView profileTitleTextView;
    ImageView profileScreenImageButton;
    boolean isEmpty;
    ProfileData data;
    String name;

    public ProfileView(Context context, AttributeSet attrs, String name, final ProfileData profileData)
    {
        super(context, attrs);
        ......
        ......
    }

    //Heres where things get complicated
    public void onClick(View v)
    {
        //Need to get the parent activity and call its method.
        ProfileActivity x = (ProfileActivity) context;
        x.activityMethod();
    }
}

ProfileActivity

public class ProfileActivityActivity extends Activity
{
    //In here I am creating multiple ProfileViews and adding them to the activity dynamically.

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.profile_activity_main);
    }

    public void addProfilesToThisView()
    {
        ProfileData tempPd = new tempPd(.....)
        Context actvitiyContext = this.getApplicationContext();
        //Profile view needs context, null, name and a profileData
        ProfileView pv = new ProfileView(actvitiyContext, null, temp, tempPd);
        profileLayout.addView(pv);
    }
}

正如您在上面看到的,我正在以编程方式实例化profileView,并将activityContext与它一起传入。两个问题:

我是否将正确的上下文传递到Profileview? 我如何从上下文获得包含活动?


当前回答

从你的Activity中,传入这个作为布局的Context:

ProfileView pv = new ProfileView(this, null, temp, tempPd);

然后你会在布局中有一个Context,但你会知道它实际上是你的Activity,你可以转换它,这样你就有了你需要的东西:

Activity activity = (Activity) context;

其他回答

这个方法应该是有用的..!

public Activity getActivityByContext(Context context){

if(context == null){
    return null;
    }

else if((context instanceof ContextWrapper) && (context instanceof Activity)){
        return (Activity) context;
    }

else if(context instanceof ContextWrapper){
        return getActivity(((ContextWrapper) context).getBaseContext());
    }

return null;

    }

我希望这能有所帮助。编码快乐!

Activity是Context的专门化,所以,如果你有一个Context,你已经知道你打算使用哪个Activity,并且可以简单地将a转换为c;其中a是活动,c是上下文。

Activity a = (Activity) c;

永远不要对视图使用getApplicationContext()。

它应该始终是activity的上下文,因为视图是附加到activity的。此外,您可能有一个自定义主题集,当使用应用程序的上下文时,所有的主题都将丢失。点击这里阅读更多不同版本的上下文。

在Kotlin中:

tailrec fun Context.activity(): Activity? = when {
  this is Activity -> this
  else -> (this as? ContextWrapper)?.baseContext?.activity()
}

对于kotlin用户-

val activity = context as Activity