Changing text from another activity

2019-01-11 19:21发布

How to dynamically 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?

4条回答
放荡不羁爱自由
2楼-- · 2019-01-11 19:59

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.

查看更多
可以哭但决不认输i
3楼-- · 2019-01-11 20:00

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.

查看更多
Animai°情兽
4楼-- · 2019-01-11 20:02

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

查看更多
贼婆χ
5楼-- · 2019-01-11 20:06

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.

查看更多
登录 后发表回答