Changing text from another activity
How to dyna开发者_Go百科mically change the content of a TextView from another part of the screen?
I have a TabActivity class that draws a RelativeLayout that contains a TextView followed by a with several tabs. Within each tab is a separate Intent. From one of the tab intents, I would like to change the text (via .setText) of the TextView from the parent TabActvity.
Is this possible?
You should use Android Architecture Components :
You can create a ViewModel containing LiveData of your data object (LiveData<String>
in case you want to change only text).
When you will change your live data object from one Activity
or Fragment
all other Activities and Fragments observing for this live data object will get notified.
Official API doc has complete example with description.
Make a public method in your TabActivity that sets the TextView's text, then call getParent()
from the child activity, cast it to your TabActivity class, then call that public method.
You could try implementing a handler for the parent Tab which does the job. Pass the text in a message object from each of your respective tabs. To be safe, make changes within the handler inside a runOnUI block
In a case of changing text from asynctask file, you need to implement an interface with a listener. Example:
AsynctaskFile:
OnReadyListener onReadyListener;
public class ABCAsynctaskFile{
...
onReadyListener.onReady();
}
public interface OnReadyListener{
void onReady();
}
public void setOnReadyListener(OnReadyListener onReadyListener){
this.onReadyListener = onReadyListener;
}
ActivityFile:
public class ABC extends AppCompactActivity implements ABCAsynctaskFile.OnReadyListener{
..
ABCAsynctaskFile aBCAsynctaskFileObj = new ABCAsynctaskFile(context);
aBCAsynctaskFile.setOnReadyListener(ABC.this)
}
@Override
public void onReady(){
// Your wished changed in edit text.
}
This structure will help you to prevent null pointer exception.
精彩评论