如何从BroadcastReceiver更新UI

时间:2017-06-25 19:24:31

标签: android broadcastreceiver

我知道如何从 BroadcastReceiver 更新UI(当BroadcaseReceiver是内部类时)。
所以这就是我想要实现的目标 (用于测试目的)我有一个活动,其LinearLayout(R.id.parent)有一个孩子TextView(R.id.text)。我想从广播接收器更新此TextView 为此我在BroadcastReceiver构造函数中传递父视图。在onReceive(Context context,Intent i)内我设置值(textView,setText("something"))。 但我得到NullPointerException。我调试它,发现构造函数中收到的View为null。我在这里缺少什么?

  

以下是代码段

public class CustomReceiver extends BroadcastReceiver {

View view;

public CustomReceiver (View v)    // <-- This v is null in Logs but it is not null in activity
{
    this.view = view;
}

@Override
public void onReceive(Context context, Intent intent) {


    if (intent.getAction().equalsIgnoreCase("Some String")) {

        TextView text= (TextView)view.findViewById(R.id.text);
         text.setText("WINTER IS COMING BRUH");
    }
}
}
  

这就是活动

protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.seach_page_layout);

    text = (TextView)findViewById(R.id.text);
    IntentFilter filter = new IntentFilter();
    filter.addAction("Some String");
    View parent = (View)findViewById(R.id.parent);
    BroadcastReceiver receiver = new CustomReceiver (parent);    
    registerReceiver(receiver ,filter);
}
  

这是布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/parent"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />
 >

<TextView
    android:id="@+id/text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />
   </LinearLayout>

2 个答案:

答案 0 :(得分:1)

  

变量'view'已分配给自身

public CustomReceiver (View v)   
{
    this.view = view; //  view -->v
}

答案 1 :(得分:0)

您无法获得这样的视图,您应该夸大TextView所在的根布局:

<html>
 <body>
    <div style="position: absolute; border: 1px solid red; background-color: white;" id="f">fixed</div>
    <div style="height:800px; background-color: #c0c0c0;"></div>
    <div style="height:800px; background-color: #f0f0f0;"></div>
    </div>
    <script>
        window.addEventListener("scroll", function() { 
            e = document.getElementById('f'); 
            e.style.top = document.body.scrollTop + 1;
        });
    </script>
  </body>
</html>

然后从视图结果中找到TextView:

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