这个让我难住了。
我需要从自定义布局类中调用一个活动方法。问题是我不知道如何从布局中访问活动。
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个问题:
从您的Activity,只需this作为Context您的布局传入:
Activity
this
Context
ProfileView pv = new ProfileView(this, null, temp, tempPd);
之后你会Context在布局中有一个,但你会知道它实际上是你的Activity,你可以投射它,这样你就有了你需要的东西:
Activity activity = (Activity) context;