我正在寻找自己的调试Activity,然后在我的其他类中使用最少量的代码从各种其他类(不仅仅是像我在这里看到的其他问题的单个类)中更新它。所以前:
// activity class
public class DebugActivity extends Activity {
public TextView txtView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView txtView = (TextView)findViewById(R.id.text);
}
public someMethod(String text) {
//Update text view code here.
}
// A class updating the text view
public class Some other class {
someOtherMethod {
DebugActivity.someMethod(updatedTextViewSTring);
}
}
答案 0 :(得分:0)
我能想到的最简单的方法是将数据(文本)发送到DebugActivity
。您需要在与<{1}}一起使用的每个 activity
中使用此代码:
DebugActivity
并接受Intent i = new Intent(this, DebugActivity.class);
i.putExtra("text", "some text");
startActivity(i);
onCreate
中的数据(文字):
DebugActivity
注意:Theres 否用于实时更改Bundle b = getIntent().getExtras();
if(b!=null)
String text = b.getString("text");
中的textview
,因为一次只显示一个Activity
。
答案 1 :(得分:0)
优雅的方法是使用EventBus lib https://github.com/greenrobot/EventBus
您需要在DebugActivity
中编写如下代码EventBus.getDefault().register(this);
public void onEventMainThread(TextEvent textEvent)
{
txtView.setText(textEvent.getText());
}
之后,您可以从App中的任何位置发送textevent,如下所示
eventBus.post(new TextEvent("my Message"));
或
Pure Android方式是使用Broadcast / Handler
答案 2 :(得分:0)
以下是如何使用广播 监视名为&#34; custom-event-name&#34;。
的事件的通知的活动@Override
public void onCreate(Bundle savedInstanceState)
{
// Register to receive messages.
// We are registering an observer (mMessageReceiver) to receive Intents
// with actions named "custom-event-name".
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,new IntentFilter("custom-event-name"));
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};
以下是您将如何从app中发送消息
// Send an Intent with an action named "custom-event-name". The Intent sent should
// be received by the ReceiverActivity.
private void sendMessage()
{
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", "This is my message!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}