I have two classes: a and b. In class ai have thread that increments the variable x by one while it's value is smaller than 1000. In class b(Activity class), i have a EditText named ed. Everytime x increments by one in class a, i want to set the text of ed from class b to x. How can this be done? See code below.
public Class a
{
int x = 0;
private void startThread()
{
MyThread = new Thread(new Runnable()
{
public void run()
{
while(x<1000)
{
x++;
//Change the text of ed from class b to x!!!!
sleep(100);
}
}
});
MyThread.start();
}
}
Class b extends Activity{
EditText ed;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ed =(EditText)findViewById(....);
}
}
IMO,您应该使用Observer模式 ,其中A
类是Observer , B
类是Subject
I don't know your application, but I have 2 suggestions:
Class A
(class names always start with a capital letter), should keep a reference to class B
, eg private final B reference
There should be anoter class that provides a reference to class B
.
EDIT
As suggested in the comment, you should use MVC . It solves your problem by nature.
public Class a
{
int x = 0;
private void startThread()
{
MyThread = new Thread(new Runnable()
{
public void run()
{
while(x<1000)
{
x++;
b.notifyEdittext(x);
sleep(100);
}
}
});
MyThread.start();
}
}
Class b extends Activity{
EditText ed;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ed =(EditText)findViewById(....);
}
public static void notifyEdittext(int counter){
if(ed!=null){
ed.setText(ed.getText()+counter);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.