从android中的上下文获取活动 [英] Getting activity from context in android
问题描述
这个让我难住了.
我需要从自定义布局类中调用活动方法.这样做的问题是我不知道如何从布局中访问 Activity.
I need to call an activity method from within a custom layout class. The problem with this is that I don't know how to access the activity from within the layout.
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个问题:
As you can see above, I am instantiating the profileView programatically and passing in the activityContext with it. 2 questions:
- 我是否将正确的上下文传递到 Profileview 中?
- 如何从上下文中获取包含的活动?
推荐答案
从你的 Activity
,只需传入 this
作为 Context
您的布局:
From your Activity
, just pass in this
as the Context
for your layout:
ProfileView pv = new ProfileView(this, null, temp, tempPd);
之后,您将在布局中拥有一个 Context
,但您会知道它实际上是您的 Activity
,您可以投射它以便获得您需要的内容:
Afterwards you will have a Context
in the layout, but you will know it is actually your Activity
and you can cast it so that you have what you need:
Activity activity = (Activity) context;
这篇关于从android中的上下文获取活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!