这绝对不是设置标题的推荐方法,但是,如果您删除分配,它应该可以工作abs = "text";
......
public class MyActivity extends SlidingFragmentActivity {
public static String abs;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle(abs);
}
}
...并在第一次创建活动之前调用MyActivity.abs = "new value";
一些地方。
无论如何,我建议将标题作为额外的活动传递给活动......
Intent intent = new Intent(context, MyActivity.class);
intent.putExtra("title", "Another Headline");
context.startActivity(intent);
...并从意图评估那个:
public class MyActivity extends SlidingFragmentActivity {
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle extras = getIntent().getExtras();
String title = "Default Headline";
if (extras != null && extras.containsKey("title")) {
title = intent.getStringExtra("title");
}
getSupportActionBar().setTitle(title);
}
}
ps创建后设置标题:
如果您可以直接引用活动,例如因为您在一个片段中,您可以添加一个类似...的方法
public class MyActivity extends SlidingFragmentActivity {
public void setTitle(String title) {
this.getSupportActionBar().setTitle(title);
}
....
}
...并相应地调用它:
getActivity().setTitle("Another Headline");
将任何类型的参数传递给现有活动以允许它们以任何方式处理它们的最复杂的方法是使用广播接收器:
public abstract class MyActivity extends SlidingFragmentActivity {
public static final String SET_TITLE_ACTION = "com.myapp.SET_TITLE_ACTION";
public static final IntentFilter INTENT_FILTER = createIntentFilter();
private SetTitleReceiver setTitleReceiver = new SetTitleReceiver();
private static IntentFilter createIntentFilter() {
IntentFilter filter = new IntentFilter();
filter.addAction(SET_TITLE_ACTION);
return filter;
}
protected void registerSetTitleReceiver() {
registerReceiver(setTitleReceiver, INTENT_FILTER);
}
protected void unRegisterSetTitleReceiver() {
unregisterReceiver(setTitleReceiver);
}
public class SetTitleReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(SET_TITLE_ACTION)) {
Bundle extras = intent.getExtras();
if (extras != null && extras.containsKey("title")) {
title = intent.getStringExtra("title");
this.getSupportActionBar().setTitle(title);
}
}
}
}
}
任何Activity
应该能够接收标题更改的类都必须在BroadcasdtReceiver
中注册onResume()
和取消注册onPause()
。这样,您可以通过从任何地方发送广播事件来设置这些活动实例的标题:
Intent intent = new Intent(MyActivity.SET_TITLE_ACTION);
intent.putExtra("title", "Another Headline");
context.sendBroadcast(intent);
希望这会有所帮助......干杯!