start activity custom preference android

旧城冷巷雨未停 提交于 2019-12-12 02:14:14

问题


I have a custom preference consisting of four imageViews. I want to start an activity when just the 4th of the 4 imageViews is clicked.

public class ImagePreference4Locks extends Preference {
public ImagePreference4Locks(final Context context, final AttributeSet attrs,
            final int defStyle) {
        super(context, attrs, defStyle);
        this.setLayoutResource(R.layout.imagepref4locks);
}

@Override
        protected void onBindView(View view) {final Context m = this.getContext();
        super.onBindView(view);

        final ImageView thumb_1 = (ImageView) view.findViewById(R.id.thumb_1);
        final ImageView thumb_2 = (ImageView) view.findViewById(R.id.thumb_2);
        final ImageView thumb_3 = (ImageView) view.findViewById(R.id.thumb_3);
        final ImageView thumb_4 = (ImageView) view.findViewById(R.id.thumb_4);
        .........

if (thumb_4 != null) {

            thumb_4.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
            /////////////////////////////////////////////
            Start Activity here:
}}

How can I start an activity here because I cant get the context.......

Using this wouldnt work:

Intent cc=new Intent(this.getContext(),HomeActivity.class);
this.getContext().startActivity(cc);

回答1:


In the constuctor you are forced to pass the context, so why don't you create a private variable such as

private static Context mContext;

and then you initialize it there?

public ImagePreference4Locks(final Context context, final AttributeSet attrs,
        final int defStyle) {
    super(context, attrs, defStyle);
    mContext = context;
    this.setLayoutResource(R.layout.imagepref4locks);
}

Now this code should work

Intent cc = new Intent(mContext, HomeActivity.class);
mContext.startActivity(cc);


来源:https://stackoverflow.com/questions/24599268/start-activity-custom-preference-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!