android - 如何从上下文中获取视图?

时间:2012-10-29 01:42:50

标签: android android-intent broadcastreceiver android-context

我想从Context获取视图或findViewById()? 还是从意图?

我正在尝试在广播接收器中访问特定视图,onReceive的参数是上下文和意图。

好吧,我有一个班级,其中有我的广播接收器。现在,我正在尝试将广播接收器与它分开,但我需要一种方法,这样我仍然可以通过我的分离广播接收器类与我班级的视图进行通信。

感谢。

5 个答案:

答案 0 :(得分:59)

例如,您可以找到任何textView:

TextView textView = (TextView) ((Activity) context).findViewById(R.id.textView1);

答案 1 :(得分:55)

从上下文开始,可以通过

获取相关活动的根视图
View rootView = ((Activity)_context).Window.DecorView.FindViewById(Android.Resource.Id.Content);

在原始Android中它看起来像:

View rootView = ((Activity)mContext).getWindow().getDecorView().findViewById(android.R.id.content)

然后只需在此

上调用findViewById
View v = rootView.findViewById(R.id.your_view_id);

答案 2 :(得分:7)

在您的广播接收器中,您可以通过膨胀从XML资源中获取根布局来访问视图,然后使用findViewByid()从此根布局中查找所有视图:

View view = View.inflate(context, R.layout.ROOT_LAYOUT, null);

现在,您可以通过“查看”访问您的观看次数并将其投放到您的观看类型:

myImage = (ImageView) view.findViewById(R.id.my_image);

答案 3 :(得分:1)

首先使用它:

LayoutInflater inflater = (LayoutInflater) Read_file.this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

Read file is current activity in which you want your context.

View layout = inflater.inflate(R.layout.your_layout_name,(ViewGroup)findViewById(R.id.layout_name_id));

然后您可以使用它来查找布局中的任何元素。

ImageView myImage = (ImageView) layout.findViewById(R.id.my_image);

答案 4 :(得分:-1)

为什么不使用单身人士?

import android.content.Context;


public class ClassicSingleton {
    private Context c=null;
    private static ClassicSingleton instance = null;
    protected ClassicSingleton()
    {
       // Exists only to defeat instantiation.
    }
    public void setContext(Context ctx)
    {
    c=ctx;
    }
    public Context getContext()
    {
       return c;
    }
    public static ClassicSingleton getInstance()
    {
        if(instance == null) {
            instance = new ClassicSingleton();
        }
        return instance;
    }
}

然后在活动类中:

 private ClassicSingleton cs = ClassicSingleton.getInstance();

在非活动课程中:

ClassicSingleton cs= ClassicSingleton.getInstance();
        Context c=cs.getContext();
        ImageView imageView = (ImageView) ((Activity)c).findViewById(R.id.imageView1);