android - 向 MainActivity 发送广播,然后显示一个 TextView [英] android - Sending a broadcast to MainActivity and then showing a TextView
问题描述
一旦在另一个视图文件中调用方法,我想取消隐藏 TextView.TextView 在 MainActivity 中.
I want to unhide a TextView once a method is called in another View file. The TextView is in MainActivity.
为此,我打算从 View 文件向 MainActivity 发送广播,但没有成功.
For this, I am planning to send a broadcast from the View file to MainActivity, but it didn't work.
我将如何实现这一目标?
How would I achieve this?
推荐答案
第 0 步:定义一个动作:
Step 0 : Define an action :
public static final String ACTION_SHOW_TEXT= "showText";
第 1 步:在 MainActivity 中创建广播接收器:
Step 1 : Create your Broadcast receiver in your MainActivity :
BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (myText != null) {
myText.setVisibility(View.VISIBLE);
}
}
};
第 2 步:在 MainActivity 中添加注册和取消注册事件:
Step 2 : Add the register and unregister events in your MainActivity :
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocalBroadcastManager.getInstance(this)
.registerReceiver(mReceiver, new IntentFilter(ACTION_SHOW_TEXT));
}
@Override
protected void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
}
第 3 步:当你想显示你的 TextView 时,从任何地方调用:
Step 3 : Whenever you want to display your TextView, call from anywhere :
Intent i = new Intent(MainActivity.ACTION_SHOW_TEXT);
i.putExtra("success", true);
LocalBroadcastManager.getInstance(this)
.sendBroadcast(i);
}
这篇关于android - 向 MainActivity 发送广播,然后显示一个 TextView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!