Android – communication between tabactivity and embedded activity
•
Android
I'm trying to find out the best communication practices between the activity and the child activities embedded in this activity
In my activity, there is a button. When I click this button, I want to update the sub activities embedded in this activity. I wrote the following code just to know if it is a good habit. Thank you
Mytabactivity.java
public class Mytabactivity extends tabactivity implements OnClickListener {
private TabHost m_tabHost;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ff_tab_activity);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
m_tabHost = getTabHost();
TabHost.TabSpec spec;
Intent intent;
intent = new Intent().setClass(this, ChildActivity.class);
spec = m_tabHost.newTabSpec("Tab 1");
spec.setContent(intent);
tabView = (TextView) inflater.inflate(R.layout.tab_indicator, null);
spec.setIndicator(tabView);
m_tabHost.addTab(spec);
m_tabHost.setCurrentTab(0);
ImageView nextButtonIv = (ImageView) findViewById(R.id.next_button);
nextButtonIv.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.next_button:
synchronized (ChildActivity.class) {
if (null != ChildActivity.s_childActivity) {
ChildActivity.s_childActivity.changeUI();
}
}
break;
}
}
ChildActivity.java
public class ChildActivity extends Activity {
public static ChildActivity s_childActivity;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
synchronized (MatchupsActivity.class) {
s_childActivity = this;
}
setContentView(R.layout.child_activity);
}
public void changeUi() {
code that changes UI
}
protected void onDestroy() {
super.onDestroy();
synchronized (MatchupsActivity.class) {
s_childActivity = null;
}
}
resolvent:
It looks good. A few notes: – I don't think there's any reason to sync. – I'll change it
ChildActivity.s_childActivity.changeUI();
with
if(ChildActivity.s_childActivity != null){
ChildActivity.s_childActivity.changeUI();
}
even to the extent that
try{
ChildActivity.s_childActivity.changeUI();
} catch(Exception e){
//log
}
Increased paranoid security
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码