小编典典

从android中的上下文获取活动

all

这个让我难住了。

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

配置文件视图

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();
    }
}

个人资料活动

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。2个问题:

  1. 我是否将正确的上下文传递到 Profileview 中?
  2. 如何从上下文中获取包含活动?

阅读 76

收藏
2022-06-30

共1个答案

小编典典

从您的Activity,只需this作为Context您的布局传入:

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

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

Activity activity = (Activity) context;
2022-06-30