I have a BaseActivity which has a ViewPager with some Fragments in it. In one of these Fragments I have 2 buttons which change the language of the app.
The thing I want to accomplish is that, on the click of the button, refresh BaseActivity to the selected language but still have the ViewPager set on Settings(name of the fragment). Right now it's reloading the entire app and starts on the fragment which I set it to start on.
Code for changing the language and refreshing the Activity
public void setLocale(String lang) {
Locale myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
SharedPreferences ensharedPreferences = getActivity().getSharedPreferences("selectedLanguage", MODE_PRIVATE);
SharedPreferences.Editor eneditor = ensharedPreferences.edit();
eneditor.putString("language", lang);
eneditor.apply();
SharedPreferences pref = getActivity().getSharedPreferences(lang,MODE_PRIVATE);
Intent refresh = new Intent(getContext(), BaseActivity.class);
getActivity().overridePendingTransition(0,0);
startActivity(refresh);
getActivity().overridePendingTransition(0,0);
}
I have only found methods on doing this the reverse way, to reload a fragment from the activity, but I want to do it the other way.
You can pass the ViewPager's selected position to the Activity using getCurrentItem() and pass it to the new Intent as an extra and reselect the item number when relaunching the Activity through getIntent() and move to the previously selected Fragment by using setCurrentItem(int position)
// Restarting the Activity passing the position of the currently selected Fragment
Intent intent = new Intent(getContext(), BaseActivity.class);
intent.putExtra(EXTRA_POSITION, viewPager.getCurrentItem());
startActivity(intent);
#Override
protected void onCreate(Bundle savedInstanceState) {
...
Intent intent = getIntent();
if(intent != null) {
int position = intent.getIntExtra(EXTRA_POSITION, 0);
viewPager.setCurrentItem(position);
}
}
Related
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_create: //run NoteActivity in new note mode
startActivity(new Intent(this, NoteActivity.class));
break;
case R.id.action_theme:
setTheme(R.style.Theme2);
setContentView(R.layout.activity_main);
Intent i = getIntent();
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
// TODO: show settings activity
break;
}
return super.onOptionsItemSelected(item);
}
I have a menu item at the top of my activity. I would like to use it to change the theme when pressed. I want to do this after the user has started the program and it will be eventually used to cycle through a bunch of different themes! Right now I just want to get it to work with one. How can I do this?
My Answer
Main Activity
SharedPreferences pref;
SharedPreferences.Editor editor;
int check;
int newcheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pref = getApplicationContext().getSharedPreferences("test", Context.MODE_PRIVATE);
check = pref.getInt("x", 0);
if(check == 0){
setTheme(R.style.AppTheme);
}else{
setTheme(R.style.Theme2);
}
setContentView(R.layout.activity_main);
noteActivity = new NoteActivity();
mListNotes = (ListView) findViewById(R.id.main_listview);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_create: //run NoteActivity in new note mode
startActivity(new Intent(this, NoteActivity.class));
break;
case R.id.action_theme:
pref = getApplicationContext().getSharedPreferences("test", Context.MODE_PRIVATE);
editor = pref.edit();
newcheck = pref.getInt("x",0);
if(newcheck == 0) {
newcheck = 1;
}else if(newcheck == 1){
newcheck = 0;
}
editor.clear();//clears the editor to avoid errors
editor.putInt("x",newcheck);//add in new int
editor.commit();//commit
//restart the activity
Intent i = getIntent();
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
finish();//close activity - avoid crash
startActivity(i);//start activity
//TODO show settings activity
break;
}
return super.onOptionsItemSelected(item);
}
So as far as I've understood your problem, you might consider thinking of taking a parent Activity and set a Fragment in there so that you can change the theme of your Fragment where the control of changing the theme is from your parent Activity. So here's how you can achieve this behaviour.
Get a fragment container in your Activity and launch your Fragment in that container in the onCreate function of your Activity.
As you're having a menu option button to decide which theme to be deployed in the Fragment you might consider replacing your Fragment again by doing another fragment transaction when your menu option is clicked.
You might consider saving the selected theme in SharedPreferences so that each time your Fragment launches, you can set the theme properly by setting it in your onCreateView function of your Fragment after reading the selected theme from your SharedPreferences.
Now if you're thinking of how you can set a theme in your Fragment then this post might help you in this regard. I'm copying the code from there for your convenience.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// create ContextThemeWrapper from the original Activity Context with the custom theme
final Context contextThemeWrapper = new ContextThemeWrapper(getActivity(), R.style.yourCustomTheme);
// clone the inflater using the ContextThemeWrapper
LayoutInflater localInflater = inflater.cloneInContext(contextThemeWrapper);
// inflate the layout using the cloned inflater, not default inflater
return localInflater.inflate(R.layout.yourLayout, container, false);
}
I hope you get the idea already. Please let me know if there's anything else you need clarification about.
The issue i have is that if i leave the adapter as an inner class of the MainActivity.I have no issues, it loads properly. If I move it out to a separate java file, then instead of populating the detail view, it launches the details activity.
Constructor
public MoviesAdapter(MovieListActivity activity, List<DummyContent.DummyItem> items, boolean twoPane) {
mActivity = activity;
mValues = items;
mTwoPane = twoPane;
}
This is how I load the details view. its in an onClick() event.
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(MovieDetailFragment.ARG_ITEM_ID, holder.mItem.id);
MovieDetailFragment fragment = new MovieDetailFragment();
fragment.setArguments(arguments);
mActivity.getSupportFragmentManager().beginTransaction()
.replace(R.id.movie_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, MovieDetailActivity.class);
intent.putExtra(MovieDetailFragment.ARG_ITEM_ID, holder.mItem.id);
context.startActivity(intent);
}
Is this common functionality or am I missing something?
I have a button on an activity called "HomePage". When you click the button, I want it to setText to a TextView called "weaponTitle" on a separate activity, called ItemSelection. Though, when I run the setText, it gives the error:
Attempt to invoke virtual method void android.widget.TextView.setText(java.lang.CharSequence) on a null object reference
So this means it can't find the TextView "weaponTitle". Is there a good way to do fix this? I have made sure I set up everything correctly too!
Here is the sliver of code I forgot to share!
new displayPrices(weaponTitle, "Genuine Freedom Staff");
try this
Firstclass
Intent intent = new Intent(getApplicationContext,SecondActivity.class);
intent.putExtra("KEY",value);
intent.putExtra("KEY",VALUE);
startActivity(intent)
Second Activity
Intent intent =getIntent();
confirm_txt =(TextView)findViewById(R.id.txt);
String txt_put =intent.getStringExtra("KEY");
confirm_tId.setText(txt_put);
Inside oncrete of your HomePage Activity
Button yourbutton = (Button) findViewById(R.id.your_button_id);
yourbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Intent intent = new Intent(HomePage.this, ItemSelection.class);
intent.putExtra("weapontitle",value);
startActivity(intent);
}
});
Inside ItemSelection Activity's oncreate
Intent intent =getIntent();
String txt =intent.getStringExtra("weapontitle");
TextView weaponTitle = (TextView) findViewById(R.id.textview_weaponTitle);
weaponTitle.setText(txt);
go through this way,
pass this from your first activity,
Intent i = new Intent(Login.this, ChangePasswordActivity.class);
i.putExtra("savedUser", savedUser);
Log.e("username", "--->>" + savedUser);
startActivity(i);
in second activity , get this as below
Intent extras = getIntent();
savedUser = extras.getStringExtra("savedUser");
Log.e("savedUser", "--->>" + savedUser);
Now you can set text as you got it on other activity.
etUsername.setText(userName);
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
intent.putExtra("weaponTitle","Genuine Freedom Staff");
startActivity(intent);
In the second activity you do:
Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
String weaponName = bundle.getString("weaponTitle");
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(weaponName);
What i am trying to do::
BreakfastLunchDinnerIndividualListOfItems.java
public class BreakfastLunchDinnerIndividualListOfItems extends TabActivity implements OnTabChangeListener{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.breakfast_lunch_dinner_individual_list_of_items);
Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Reusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab
String REST = getTabHost().toString();
// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, BLD_IndividualListOfItems_Starters.class);
//intent.putExtra("Starters", REST);
spec = tabHost.newTabSpec("Starters").setIndicator("Starters").setContent(intent);
tabHost.addTab(spec);
// Do the same for the other tabs
intent = new Intent().setClass(this, BLD_IndividualListOfItems_MainCourse.class);
//intent.putExtra("MainCourse", REST);
spec = tabHost.newTabSpec("MAIN_COURSE").setIndicator("Main Course").setContent(intent);
tabHost.addTab(spec);
}
public void onTabChanged(String arg0)
{
// TODO Auto-generated method stub
//Toast.makeText(getApplicationContext(),arg0, Toast.LENGTH_LONG).show();
}
}
I tried with String REST = getTabHost().toString(); problem is that
on click of tab i am not able to send perticular tabtext to the
activity that the tab launches
I know tab activity is depricated, i am just learning
How to resolve this, hope i am clear
spec = tabHost.newTabSpec("Starters").setIndicator("Starters").setContent(intent);
spec = tabHost.newTabSpec("MAIN_COURSE").setIndicator("Main Course").setContent(intent);
here Starters and Main Course are the titles of tabs. The easiest way to send this strings to bounded activities is to send them throught intents which are bounded to corresponding
tabSpecs.
String TAB_TITLE="Starters";
Intent intent = new Intent().setClass(this, BLD_IndividualListOfItems_Starters.class);
Bundle bundle =new Bundle();
bundle.putString("key_title", TAB_TITLE);
intent.putExtras(bundle);
spec = tabHost.newTabSpec("Starters").setIndicator(TAB_TITLE).setContent(intent);
tabHost.addTab(spec);
And here is how you can get this string in BLD_IndividualListOfItems_Starters activity :
protected void onCreate(Bundle savedInstanceState) {
...
String title=getIntent().getExtras().getString("key_title");
}
But as Raghunandan says, it's better to use fragments instead of depracated TabActivity.
EDITED:
if you want to send text to corresponding activity dinamically, i mean exactly after tab is changed - you can:
create and broadcast custom intent with your string. (CUSTOM_INTENT_EXAMPLE)
in BLD_IndividualListOfItems_Starters activity register BroadcastReciever which will catch your custom intent and take text from it. (BROADCAST_RECIEVER_FROM_ACTIVITY_EXAMPLE)
You can't directly access tab text from BLD_IndividualListOfItems_Starters, because TabActivity and BLD_IndividualListOfItems_Starters are two different activities.
But you can send data between activities via bundles, static fields, singletons etc. Here is link to docs
http://developer.android.com/guide/faq/framework.html#3
I am currently learning Android app development and I am a bit confused on how to use Intent. I am trying to make a "To Do list" app. My problem right now is that I want to be able to tap the item in my to do list to go to a Edit Item page.
Here is what I have so far.
ToDoActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to_do);
etNewItem = (EditText) findViewById(R.id.etNewItem);
lvItems = (ListView) findViewById(R.id.lvItems); // now we have access to ListView
readItems(); // read items from file
todoAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoItems); //create adapter
lvItems.setAdapter(todoAdapter); // populate listview using the adapter
setupListViewListener();
setupEditItemListener();
}
The activity I want to launch is called EditItemListener. These are the two functions that I am playing Intent with. Right now I am just testing how to display the EditItemActivity.
private void launchEditItem() {
Intent i = new Intent(this, EditItemActivity);
startActivity(i);
}
private void setupEditItemListener() { // on click, run this function to display edit page
lvItems.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
launchEditItem();
}
});
}
You should specify it as a class
Intent i = new Intent(this, EditItemActivity.class);
Also if you want to kill the current activity
use finish() after StartActivity()
on a listview set the OnItemClickListener and on the listener do this
Intent i = new Intent(this, YourActivity.class); //where you are (this) and where you go (YourAcitivity.class)
startActivity(i); //Now GO!
The intent will start another activity, this activity must be declared on AndroidMainfest.xml