pass string from fragment main activity to fragments activity in viewpager - android

i wanna pass a string to all fragment(child) from fragment activity (main), may be this picture can explain what exactly what i want to do
https://dl.dropboxusercontent.com/u/57465028/SC20140205-163325.png
so, from above picture...i wanna pass a string from edittext by press a button to all activity in viewpager....how could i do that?
i tried to follow this code https://stackoverflow.com/a/12739968/2003393 but it can't solved my problem..
please help me...i'm stuck
thank in advance.
here is my code from fragment activity (MainActivity)
public class Swipe_Menu extends FragmentActivity {
//String KeyWord;
//private static final String KEYWORD = "keyword";
private ViewPager _mViewPager;
private ViewPagerAdapter _adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.swipe_menu_image);
Button Back = (Button)findViewById(R.id.account);
ImageButton Search = (ImageButton)findViewById(R.id.search);
EditText Keyword = (EditText)findViewById(R.id.keyword);
final String KeyWord = Keyword.getText().toString();
/**
* Back button click event
* */
Back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
finish();
}
});
setUpView();
setTab();
}
protected void sendValueToFragments(String value) {
// it has to be the same name as in the fragment
Intent intent = new Intent("my_package.action.UI_UPDATE");
intent.putExtra("UI_KEY", KeyWord );
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
and here is my fragment (Child Activity)
public class Store_Swipe extends Fragment {
public static final String ACTION_INTENT = "my_package.action.UI_UPDATE";
String KeyWord;
private TextView kata_keyword;
protected BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(ACTION_INTENT.equals(intent.getAction())) {
String value = intent.getStringExtra("UI_KEY");
updateUIOnReceiverValue(value);
}
}
};
private void updateUIOnReceiverValue(String value) {
// you probably want this:
KeyWord = value;
}
public static Fragment newInstance(Context context) {
Store_Swipe f = new Store_Swipe();
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter(ACTION_INTENT);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, filter);
}
#Override
public void onDestroy() {
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);
super.onDestroy();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/*Bundle bundle = this.getArguments();
KeyWord = bundle.getString("keyword");*/
View view = inflater.inflate(R.layout.store_swipe, container, false);
init(view);
return view;
}
void init(View view) {
kata_keyword = (TextView) view.findViewById(R.id.keyword);
//ImageView image = (ImageView) view.findViewById(R.id.image_error);
kata_keyword.setText(KeyWord);
}
}

You don't have access directly to your fragments that reside in ViewPager so you can't reference them directly.
What I am doing in these cases is send a broadcast message from Activity to Fragments. For this reason register a BroadcatReceiver in the fragment (either in onCreate or onCreateView - your decision)m, set a custom action for that receiver (ex. "my_package.actions.internal.BROADCAST_ACTION"), don't forget to unregister the receiver from complementary method.
When you want to send a message from activity, create an intent with above mentioned action, add the string in intent extra and send the broadcast.
In your receiver's onReceive method (within the fragment), get the String from intent paramter and there you have the string.
Makes sense?
EDIT: To provide some code, below are the changes that I would make for fragment:
public class Store_Swipe extends Fragment {
public static final String ACTION_INTENT = "my_package.action.UI_UPDATE";
protected BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(ACTION_INTENT.equals(intent.getAction())) {
String value = intent.getStringExtra("UI_KEY");
updateUIOnReceiverValue(value);
}
}
};
private void updateUIOnReceiverValue(String value) {
// you probably want this:
kata_keyword.setText(value);
}
String KeyWord;
private TextView kata_keyword;
public static Fragment newInstance(Context context) {
Store_Swipe f = new Store_Swipe();
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter(ACTION_INTENT);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, filter);
}
#Override
public void onDestroy() {
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);
super.onDestroy();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle bundle = this.getArguments();
KeyWord = bundle.getString("keyword");
View view = inflater.inflate(R.layout.store_swipe, container, false);
init(view);
return view;
}
void init(View view) {
kata_keyword = (TextView) view.findViewById(R.id.keyword);
ImageView image = (ImageView) view.findViewById(R.id.image_error);
kata_keyword.setText(KeyWord);
}
}
And this code I would have from activity, the parameter is the value from EditText:
protected void sendValueToFragments(String value) {
// it has to be the same name as in the fragment
Intent intent = new Intent("my_package.action.UI_UPDATE");
intent.putExtra("UI_KEY", value);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
You would call this from the click listener that you would set in onCreate:
findViewById(R.id.button_id).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String valueThatYouWantToSend = null; /// just the value
sendValueToFragments(valueThatYouWantToSend);
}
});

// I think this solution will solved your issue
// In Main activity put your code -----------------------------------
public void onPageSelected(int position)
{
System.out.println("nilesh");
PageOneFragment f = new PageOneFragment();
f.getText();
PageTwoFragment ff = new PageTwoFragment();
ff.setText();
}
//in General Class ------------------------------------------------
public class General
{
public static String name="";
}
// first Fragment ---------------------------------------------
public void getText()
{
General.name = edittext.getText().toString();
}
// second Fragment ----------------------------------------------
public void setText()
{
System.out.println("name**" + General.name);
tv.setText(General.name);
}

Related

passing data from (grand) parent to parent to child to (grand) child and back up to (Grand) parent activity in android

I have a grand parent activity called Department
public class Department extends AppCompatActivity {
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_department);
.........
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, DeptDetail.class);
Bundle extra = new Bundle();
extra.putString("Department", getAdapterPosition()+"");
intent.putExtras(extra);
context.startActivity(intent);
}
});
}
}
Sends data about Department position to DepartmentDeatail activity
public class DeptDetail extends AppCompatActivity implements View.OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dept_detail);
Bundle extra = getIntent().getExtras();
deptpos = Integer.parseInt(extra.getString("Department"));
.........
public void onClick(View v) {
int id= v.getId();
Intent in;
Bundle extras = new Bundle();
in = new Intent(DeptDetail.this, Mission.class);
extras.putString("Mission",mission[deptpos]);
extras.putString("Deptid", deptpos+"");
in.putExtras(extras);
startActivityForResult(in,1);
}
}
and DeptDetail activity sends same Deptpos to its child activity Mission
public class Mission extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mission);
Bundle extra = getIntent().getExtras();
String mission = extra.getString("Mission");
deptid=Integer.parseInt(extra.getString("Deptid"));
TextView txtmission = (TextView)findViewById(R.id.txtmission);
try {
txtmission.setText(mission);
}
catch (NullPointerException e)
{
txtmission.setText("");
}
}
}
And now I want same Deptid to be accessed in DeptDetail activity which always calls for intent from Department activity, which is not available as usual..
So please show me the way to pass the data to child and back to parent.
I tried
onActivityResult(..)
but it wasn't called before onCreate where extra is read and generating NullPointerException

Custom DialogFragment is not working

I am trying to create a custom dialog using dialogFragment, here I am not be able to display the dialog. The main problem is overriden code is not getting called. Can anyone fix this issue. Here is my code:
BaseDialogFragment.java
public class BaseDialogFragment extends DialogFragment {
private int layoutId;
protected Activity mActivity;
public void setLayoutId(int layoutId){
this.layoutId = layoutId;
}
public BaseDialogFragment(){
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setStyle(BaseDialogFragment.STYLE_NO_TITLE, R.style.share_dialog);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState){
View v = inflater.inflate(layoutId, container, false);
return v;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mActivity = activity;
}
public void initViews(View v){
getDialog().setCanceledOnTouchOutside(true);
}
}
CustomDialog.java:
#SuppressLint("ValidFragment")
public class CustomDialog extends BaseDialogFragment {
private String message;
private btnOkClick okClickListerner;
private TextView simpleMsg;
private WebView termsConditionWeb;
private Button okBtn;
Boolean isNormalDialog = false;
private Typeface fontClanProBold;
private View v;
private Context context;
public interface btnOkClick{
void clicked();
}
public CustomDialog(String message, btnOkClick okClickListerner, Boolean isNormalDialog){
this.message = message;
this.okClickListerner = okClickListerner;
this.isNormalDialog = isNormalDialog;
this.mActivity = null;
setLayoutId(R.layout.activity_custom_dialog);
initViews(v);
}
#Override
public void initViews(View v) {
super.initViews(v);
this.simpleMsg = (TextView) v.findViewById(R.id.simpleMsg);
this.termsConditionWeb= (WebView) v.findViewById(R.id.termsConditionWeb);
this.okBtn = (Button) v.findViewById(R.id.okBtn);
fontClanProBold = Typeface.createFromAsset(context.getAssets(), "fonts/ufonts.com_clanpro-bold.ttf");
Log.e("isNormal", isNormalDialog.toString());
if(isNormalDialog){
this.simpleMsg.setVisibility(View.VISIBLE);
this.simpleMsg.setText(message);
this.simpleMsg.setTypeface(fontClanProBold);
} else {
this.termsConditionWeb.setVisibility(View.VISIBLE);
this.termsConditionWeb.loadData(message, "text/html", "UTF-8");
}
setCancelable(false);
initEvent(v);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.mActivity = activity;
}
private void initEvent(View v){
okBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(okClickListerner != null){
okClickListerner.clicked();
}
dismiss();
}
});
}
public static void ShowDialog(FragmentManager fm, String message, btnOkClick okClickListerner, Boolean isNormalDialog){
CustomDialog dialog = new CustomDialog(message, okClickListerner, isNormalDialog);
dialog.show(fm, "");
}
}
MainActivity.java
inside a onClickListener
CustomDialog.ShowDialog(getSupportFragmentManager(), getResources().getString(R.string.message_register), new CustomDialog.btnOkClick() {
#Override
public void clicked() {
finish();
}
}, isNormalDialog);
It is bad practice to set values inside your Dialog constructor. Instead pass your values as arguments and initialize them on onCreate callback. Furthermore, you shall avoid saving instances of your activity on your fragment, it may lead to memory leaks. Instead I recomend you to create an interface on your CustomDialog or in your BaseDialogFragment that all activitys that uses them must implement. Then you need to implemnt onClickListener interface on your Dialog and inside it you can call mListener.onButtonClickListener(). See the example DialogFragment.
Your CustomDialog would look something like:
public class CustomDialog extends BaseDialogFragment {
private myFragmentInterface mListener;
public static CustomDialog newInstance(String message, Boolean isNormalDialog){
Bundle args = new Bundle();
args.putString(MESSAGE_ARG_KEY, message);
args.putBoolean(TYPE_ARG_KEY, isNormalDialog);
CustomDialog instance = new CustomDialog();
instance.setArguments(args);
}
#override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
message = getArguments().getStirng(MESSAGE_ARG_KEY);
isNormalDialog = getArguments().getBoolean(TYPE_ARG_KEY);
}
#override
public void onAttach(Activity activity){
super.onAttach();
try{
mListener = (myFragmentInterface) activity;
}catch(ClassCastException e){
throw new ClassCastException("activiy must implement myFragmentInterface");
}
}
public void onDetach(){
super.onDetach();
mListener = null;
}
public interface myFragmentInterface{
onButtonClickListener(String... params);
}
}

OnDestroy exception in Main Activity using Android fragment

I am having a "Receiver no registered exception" in OnDestroy method of my app using fragments.
I have a MainActiviy class where I check if the user registered an account.
If not account created, I load the register account class fragment to allow the user create an account.
After the user create the account clicking a button I restart the MainActivity class.
I need to register a broadcastreceiver only after the user create an account.
But, after the restart the MainActivity class from Frgamnent Class, I am getting an exception of receiver not registered in event OnDestroy of Main Activity.
Any help to solve it will be appreciated.
Thanks in Advance, Luiz
My MainActivity Class
public class MainActivity extends Activity {
// if run on phone, isSinglePane = true
// if run on tablet, isSinglePane = false
static boolean isSinglePane;
private GcmUtil gcmUtil;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View v = findViewById(R.id.phone_container);
if (!AccountRegisterCreated()){
//this fragmment register an account to user, and save in Preferences
RegisterFragment myListFragment= new RegisterFragment();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.phone_container, myListFragment);
fragmentTransaction.commit();
return;
}
registerReceiver(registrationStatusReceiver, new IntentFilter(Common.ACTION_REGISTER));
}
private BroadcastReceiver registrationStatusReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null && Common.ACTION_REGISTER.equals(intent.getAction())) {
switch (intent.getIntExtra(Common.EXTRA_STATUS, 100)) {
case Common.STATUS_SUCCESS:
getActionBar().setSubtitle("online");
break;
case Common.STATUS_FAILED:
getActionBar().setSubtitle("offline");
break;
}
}
}
};
#Override
protected void onPause() {
ContentValues values = new ContentValues(1);
super.onPause();
}
#Override
protected void onDestroy() {
unregisterReceiver(registrationStatusReceiver);
super.onDestroy();
}
private boolean AccountRegisterCreated(){
SharedPreferences prefs;
prefs= PreferenceManager.getDefaultSharedPreferences(this);
String fullname = prefs.getString(DataProvider.COL_EMAIL,"");
if (!fullname.isEmpty()) {
return true;
}
return false;
}
}
My Fragment Class:
public class RegisterFragment extends Fragment {
private static SharedPreferences prefs;
static final String TAG = "pushabout";
TextView name;
TextView email;
TextView password;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.register, null);
name = (TextView) view.findViewById(R.id.reg_fullname);
email = (TextView) view.findViewById(R.id.reg_email);
password = (TextView) view.findViewById(R.id.reg_password);
if (email.getText().toString().isEmpty()){
email.setText(Common.getPreferredEmail());
}
Button mButton = (Button) view.findViewById(R.id.btnRegister);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//checa email e reg e salva pref e registra gcm
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = prefs.edit();
editor.putString(DataProvider.COL_NAME, sname);
editor.putString(DataProvider.COL_EMAIL, semail);
editor.putString(DataProvider.COL_PWD, spassword);
editor.commit();
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
return view;
}
}
The problem is not with the Fragment. It's the BroadcastReceiver in your Activity.
Try declaring your BroadcastReceiver as a class field:
public class MainActivity extends Activity {
...
BroadcastReceiver mBroadcastReceiver;
...
Then, you should change how you're creating and registering the receiver. The way I've done it is by registering during the activity's onResume instead of onCreate(). If you do this, you'll also need to unregister during onPause() instead of onDestroy(). It will look something like this:
#Override
public void onResume() {
super.onResume();
// Create and register your receiver here.
if (AccountRegisterCreated) {
mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
....
}
}
registerReceiver(mBroadcastReceiver, new IntentFilter(Common.ACTION_REGISTER));
}
...
}
#Override
public void onPause() {
super.onPause();
// Unregister your receiver here
if (mBroadcastReceiver != null) {
unregisterReceiver(mBroadcastReceiver);
}
}
Just declare a member variable of type boolean. When you register the BroadcastReceiver, set that variable to true. In onDestroy() only call unregisterReceiver() if the variable is true.

Trying to access a Fragment from another thread to change TextView text

I am making an app that is using Fragments and wish to change the text in a TextView based on a message received in a client thread communicating with a laptop. The client server communication is no issue as the client thread is receiving the strings just fine.
I can't seem to properly figure out how to access the fragments TextView and alter its text.
Here is how I am currently trying to do so:
class ClientThread implements Runnable {
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
LivingRoomFragment frag = (LivingRoomFragment)getSupportFragmentManager().findFragmentById(R.id.LivingRoomFragment);
frag.setText("Inside ClientThread right now");
}
});
}
}
public static class LivingRoomFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
TextView temp;
public LivingRoomFragment(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_room_control_fragment1, container, false);
temp = (TextView) rootView.findViewById(R.id.textView5);
MainActivity main = new MainActivity();
new Thread(main.new ClientThread(requests)).start();
return rootView;
}
public void setText(String s){
temp.setText(s);
}
}
In this case, MainActivity is the activity extending FragmentActivity.
I'm using an emulator and the app always crashing saying there was a null pointer exception at the line using frag.setText("Inside ClientThread right now"), which I believe means that the instance of LivingRoomFragment is null. It is to my understanding so far that this is supposed to be executed using a Handler because you cannot access the UI from a thread without using a method like this.
What am I doing wrong?
I am not sure, try
MainActivity main = (MainActivity)getActivity;
instead of
MainActivity main = new MainActivity();
okay Toast.
now here is your Solution.
create Broadcast Receiver in your Fragments.
create your action,action is an key which diffrenciat your broadcast.
use below sample code.(you do not have post more code,so it may not ecxatly what you want okay?)
class ClientThread implements Runnable {
private Handler mHandler;
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
Intent intent = new Intent("my_action");
intent.putExtra("message", "TEXT_YOU_WANT_TO_SET");
sendBroadcast(intent);
// LocalBroadcastManager manager = LocalBroadcastManager
// .getInstance(context);
// LivingRoomFragment frag = (LivingRoomFragment)
// getSupportFragmentManager()
// .findFragmentById(R.id.LivingRoomFragment);
// frag.setText("Inside ClientThread right now");
}
});
}
}
public static class LivingRoomFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
TextView temp;
private MyBroadCastReceiver broadCastReceiver;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
broadCastReceiver = new MyBroadCastReceiver();
getActivity().registerReceiver(broadCastReceiver,
new IntentFilter("my_action"));
}
public LivingRoomFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.activity_room_control_fragment1, container, false);
temp = (TextView) rootView.findViewById(R.id.textView5);
MainActivity main = new MainActivity();
new Thread(main.new ClientThread(requests)).start();
return rootView;
}
public void setText(String s) {
temp.setText(s);
}
private class MyBroadCastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent intent) {
// chaneg the TextView text here
if (intent.getAction() != null
&& intent.getAction().equalsIgnoreCase("my_action")) {
temp.setText(intent.getStringExtra("message"));
}
}
}
}
good luck.

Change getSupportActionBar().setTitle value from another class

I have a class that gets actionbarsherlock oncreate and sets default values. How can I change this values from another class ?
sample codes that doesnt work :
public class MyActivity extends SlidingFragmentActivity {
public static String abs;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
abs = "text";
getSupportActionBar().setTitle(abs);
}
}
External class:
MyActivity.abs = "new value";
It is definitely not the recommended way to set the title, however, it should work if you remove the assignment 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);
}
}
... and call MyActivity.abs = "new value";some where before the activity is created the first time.
Anyhow I'd propose to pass the title as an extra into the activity ...
Intent intent = new Intent(context, MyActivity.class);
intent.putExtra("title", "Another Headline");
context.startActivity(intent);
... and evaluate that one from the 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);
}
}
p.s. setting title after creation:
If you can reference the activity directly, for instance because you are in a fragment, you might add a method like ...
public class MyActivity extends SlidingFragmentActivity {
public void setTitle(String title) {
this.getSupportActionBar().setTitle(title);
}
....
}
... and call it accordingly:
getActivity().setTitle("Another Headline");
The most sophisticated way to pass any kind of arguments to existing activities allowing them to process them in any way would be using a BroadcastReceiver:
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);
}
}
}
}
}
Any Activity class that should be able to receive a title change has to register the BroadcasdtReceiver in onResume() and unregister it in onPause(). This way you can set the title of these activity instance by sending a broadcast event from anywhere:
Intent intent = new Intent(MyActivity.SET_TITLE_ACTION);
intent.putExtra("title", "Another Headline");
context.sendBroadcast(intent);
Hope this helps ... Cheers!
It doesn't work because your just changing the reference abs is pointing to.
If you want to change the title pass the SherlockActivity as a parameter to your method.
Example:
public class MyActivity extends SherlockActivity {
#Override
protected void onCreate(final Bundle savedInstanceState) {
new ChangeTitle(this).setTitle("test title");
}
}
class ChangeTitle {
String title;
SherlockActivity activity;
public ChangeTitle(SherlockActivity activity) {
this.activity = activity;
}
public void setTitle(String title) {
this.title = title;
activity.getSupportActionBar().setTitle(this.title);
}
}

Categories

Resources