I would like to get the value of my checkbox that is in my confiFragment and get that value in MainActivity .
The configFragment is related to the confiActivity.
I tried this method but i get a null ; can someone help me please?
This is my fragment:
public class configFragment extends android.support.v4.app.Fragment {
CheckBox check;
configActivity cmt;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.config_layout, container, false);
check = (CheckBox) rootView.findViewById(R.id.checkbox1);
TextView text1=(TextView) rootView.findViewById(R.id.text1);
text1.setText("hello ");
cmt=(configActivity) getActivity();
check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(check.isChecked()){
Log.d("status","checked");
//check.setChecked(true);
cmt.checking=true;
}else{
Log.d("status","not checked");
//check.setChecked(false);
cmt.checking=false;
}
}
});
//cmt.checking=load();
// check();
return rootView;
}
#Override
public void onPause() {
super.onPause();
save(check.isChecked());
}
#Override
public void onResume() {
super.onResume();
check.setChecked(load());
}
private void save(final boolean isChecked) {
SharedPreferences sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("check", isChecked);
editor.commit();
}
public boolean load() {
SharedPreferences sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
return sharedPreferences.getBoolean("check", check.isChecked());
}
}
and this is the activity of this fragment:
public class configActivity extends SingleFragmentActivity {
public Boolean checking;
#Override
protected Fragment createFragment()
{
return new configFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
configFragment cf=new configFragment();
SharedPreferences sharedPreferences = this.getPreferences(Context.MODE_PRIVATE);
checking=sharedPreferences.getBoolean("check", cf.check.isChecked());
}
}
and this is my main activity :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView hello=(TextView) findViewById(R.id.hello);
Button but1=(Button) findViewById(R.id.button1);
but1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(MainActivity.this,configActivity.class);
startActivity(i);
}
});
hello.setText("Hello world");
configActivity config=new configActivity();
Log.d("status of checking",config.checking.toString());
if(config.checking=true){
Log.d("checked","true");
}else{
Log.d("not checked","false");
}
}
You using a wrong way to create communication between fragment to activity.
The correct way to communicate between your activity and fragments is using interfaces.
Define an interface in your configFragment and then implement that in your activity.
And do what ever you want.
Refer this
And if you want to pass this is to your main activity set a Result to main activity from your configActivity. Refer this one for starting activity for result
And also go through this link. Ho to use fragment
Related
I am having a fragment that contains for example one button, I want to allow the Activity containing the fragment to change this button view like for example color and title or src Image.
What's the best way to do that ?
Update : sorry If I wasn't clear enough but I want the activity to change the whole view as it's likes , like setting the padding, the color or anything.
It will create the view programmatically and the fragment should replace the old view by the new one and change the view's ID so that the fragment code isn't affected. And If i created methods in the fragment that takes these views when should the Main activity call them ? since the activity has to wait for the layout of the fragment to be created.
1. You must get you fragment from your activity
val fragment = supportFragmentManager.findFragmentByTag("tag")
or
val fragment = supportFragmentManager.findFragmentById(R.id.fragment)
2. Create a method that will do what you wants in you fragment and call this method from the activity
fragment.hideButton()
or you can use interface
Try this way according to your requirement
public abstract class BaseFragment extends Fragment {
BaseActivity yourActivity;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
yourActivity = (BaseActivity) context;
}
#Override
public void onDetach() {
yourActivity = null;
super.onDetach();
}
public void refreshview(){}
public void setDada(Data data){}
#override
publicn void onStart(){
yourActivity.setCurrentOpenedFragment(this);
}
}
Create the BaseActivity class
public abstract class BaseActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void setCurrentOpenedFragment(BaseFragment currentFragment){}
}
Extends the BaseFragment in your fragment i.e.
public class YourFragment extends BaseFragment{
View view;
Button button;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment, container, false);
button = (Button)view.findViewById(R.id.button);
return view;
}
#override
publicn void onStart(){
super.onStart();
//yourActivity.setCurrentOpenedFragment(this);
}
Data data;
#override
public void setDada(Data data){
this.data = data;
}
#Override
public void refreshview() {
button.setcolor(data.getcolor());
}
}
Write the below line of code in your Activity class
public class YourActivity extends BaseActivity{
public static final byte NONE = -1;
public static final byte HOME = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity);
changeFragment(new YourFragment(), HOME);
initview();
}
public void initview(){
Button b = (Button)findViewById(R.id.button);
b.setOnClickListener(new OnClickListener(){
if(currentFragmentOnDrawer != null){
Data data = new Data();
data.setColor(getResource().getcolor(R.color.red));
currentFragmentOnDrawer.setDada(data);
currentFragmentOnDrawer.refreshview()
}
});
}
BaseFragment currentFragmentOnDrawer;
#Override
public void setCurrentOpenedFragment(BaseFragment currentFragment) {
super.setCurrentOpenedFragment(currentFragment);
this.currentFragmentOnDrawer = currentFragment;
}
public void changeFragment(Fragment targetFragment, byte state) {
FragmentTransaction ft = getSupportFragmentManager()
.beginTransaction();
ft.replace(R.id.main_fragment, targetFragment, "" + state);
ft.addToBackStack("" + state);
ft.commit();
}
}
Hope it will help for you
I'm trying to update my app background color by changing the preferences but the method onSharedPreferenceChanged is never reached. The preferences are changed successfully, but I the listener doesn't work properly:
MainActivity:
public class MainActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
private RecyclerView mRecyclerView;
private ContactsAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public void onResume() {
super.onResume();
SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences(this);
mSettings.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
mSettings.unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent = new Intent(this, MyPreferenceActivity.class);
startActivity(intent);
return true;
case R.id.action_favorite:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.equals("color")) {
String color = sharedPreferences.getString("color", "3");
int colorId = Integer.valueOf(color);
// Alterar background
ViewGroup viewGroup = (ViewGroup) ((ViewGroup) (findViewById(android.R.id.content))).getChildAt(0);
if (colorId == 1) {
viewGroup.setBackgroundColor(Color.WHITE);
} else if (colorId == 2) {
viewGroup.setBackgroundColor(Color.YELLOW);
} else if (colorId == 3) {
viewGroup.setBackgroundColor(Color.RED);
}
}
}
}
MyPreferenceActivity:
public class MyPreferenceActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference);
}
}
The method onSharedPreferenceChanged is never called, the only way I got it to work was implement the method OnSharedPreferenceChangeListener directly inside the onResume, but sometimes it works fine, sometimes it doesn't and the method is not reached.
The Shared preference registerOnSharedPreferenceChangeListener is valid only when MainActivity is in foreground else that will be unregistered in onPause.
When you are creating a PreferenceActivity named MyPreferenceActivity, the onPause() of MainActivity is called, where the listener is getting unregistered.
One work around could be, unregister from the listener onStop() instead onPause() in MainActivity.
MainActivity.java
#Override
public void onStart() {
super.onStart();
SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences(this);
mSettings.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onStop() {
super.onStop();
SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
mSettings.unregisterOnSharedPreferenceChangeListener(this);
}
Hey I'm trying to add an onSharedPreference Listener into n Fragment. It should regulate if a change is done (switch in the settings) the value of the NumberPicker inside the Fragment changes(0 or 1) too.
the problem with the listener: it only works the first 5-10 times then it doesnt get called anymore (i suppose)? -> no changes done on NumberPicker
following the importants code of my fragment:
public class FragmentTwo extends Fragment {
private EditText mEnterWeight;
private NumberPicker mUnitPicker;
private TextView mConverted;
private int pick;
private String convertedWeightMessage;
private Double enteredWeight;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_two, container, false);
mEnterWeight = (EditText) view.findViewById(R.id.WCenterWeight);
mUnitPicker = (NumberPicker) view.findViewById(R.id.WCunitPicker);
mConverted = (TextView) view.findViewById(R.id.WCconverted);
initialiseUnitPicker();
//some stuff
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
// listener implementation
if(key.equals("SwitchMainUnit")) {
Boolean kg = prefs.getBoolean("SwitchMainUnit", true);
if(kg)
mUnitPicker.setValue(0);
else mUnitPicker.setValue(1);
}
}
};
prefs.registerOnSharedPreferenceChangeListener(listener);
return view;
}
The docs say that i need to change the onResume() and onPause() to:
#Override
protected void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
But where do i need to add these? Got errors when i tried to add it in the Fragment.
Thanks for helping; didnt come to any solution myself.. :/
The documentation says
Caution: When you call registerOnSharedPreferenceChangeListener(), the
preference manager does not currently store a strong reference to the
listener
I recommend that you store your instance of SharedPreferences.OnSharedPreferenceChangeListener listener as a field outside of onCreateView.
Example code:
public class FragmentTwo extends Fragment {
private EditText mEnterWeight;
private NumberPicker mUnitPicker;
private TextView mConverted;
private int pick;
private String convertedWeightMessage;
private Double enteredWeight;
SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
// listener implementation
if (key.equals("SwitchMainUnit")) {
Boolean kg = prefs.getBoolean("SwitchMainUnit", true);
if (kg) mUnitPicker.setValue(0);
else mUnitPicker.setValue(1);
}
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_two, container, false);
mEnterWeight = (EditText) view.findViewById(R.id.WCenterWeight);
mUnitPicker = (NumberPicker) view.findViewById(R.id.WCunitPicker);
mConverted = (TextView) view.findViewById(R.id.WCconverted);
initialiseUnitPicker();
//some stuff
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
prefs.registerOnSharedPreferenceChangeListener(listener);
return view;
}
I'm trying to develop an application that has a PreferenceActivity two CheckBoxPreference and MainActivity . I want that when you selections and some of them go out to MainActivity , saved, and again she selected only see you 've selected first. I tried all things but nothing work. Help me!!
My code:
public class Preferencias extends PreferenceActivity implements OnPreferenceChangeListener{
Boolean bmusica=true,bvibracion=true;
SharedPreferences prefs;
CheckBoxPreference chMusica,chVibr;
SharedPreferences.Editor gg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferencias);
if(savedInstanceState!=null){
chMusica.setChecked(savedInstanceState.getBoolean("estadoMusica"));
bmusica=savedInstanceState.getBoolean("valorMusica");
chVibr.setChecked(savedInstanceState.getBoolean("estadoVibracion"));
bvibracion=savedInstanceState.getBoolean("valorVibr");
}else{
prefs =this.getPreferenceManager().getSharedPreferences();
gg= prefs.edit();
chMusica = (CheckBoxPreference) findPreference("musica");
chVibr = (CheckBoxPreference) findPreference("vibracion");
chMusica.setChecked(true);
chVibr.setChecked(true);
}
}
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
if(chMusica.isChecked()){
gg.putBoolean("musica", true);
bmusica=true;
}else{
gg.putBoolean("musica", false);
bmusica=false;
}
if(chVibr.isChecked()){
gg.putBoolean("vibracion", true);
bvibracion=true;
}else{
gg.putBoolean("vibracion", false);
bvibracion=false;
}
return true;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean("estadoMusica", chMusica.isChecked());
outState.putBoolean("valorMusica", bmusica);
outState.putBoolean("estadoVibracion", chVibr.isChecked());
outState.putBoolean("valorVibr", bvibracion);
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
chMusica.setChecked(state.getBoolean("estadoMusica"));
chVibr.setChecked(state.getBoolean("estadoVibracion"));
bmusica=state.getBoolean("valorMusica");
bvibracion=state.getBoolean("valorVibr");
}
And my MainActivity:
public class MainActivity extends Activity {
Button jugar, preferencias, acercade, maximo, salir;
Vibrator v;
Boolean isVibrar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_land);
v = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
jugar = (Button) findViewById(R.id.botonJugar);
preferencias = (Button) findViewById(R.id.botonOpciones);
acercade = (Button) findViewById(R.id.botonAcercaDe);
maximo = (Button) findViewById(R.id.botonPuntuaciones);
salir = (Button) findViewById(R.id.botonSalir);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
isVibrar = sharedPref.getBoolean("vibracion", true);
public void preferencias(View view) {
if (isVibrar==true) {
v.vibrate(200);
}
Intent i = new Intent(MainActivity.this, Preferencias.class);
startActivity(i);
}
I'm trying return a String from the DialogFragment, following this instructions https://stackoverflow.com/a/14808425/2933117 , but I only get logcat error
java.lang.ClassCastException: com.example.testinterface.MainActivity cannot be cast to com.example.testinterface.InterDialog$EditNameDialogListener
I appreciate any help or explanation of why I get an error, thanks in advance.
Here is my code:
MainActivity
public class MainActivity extends FragmentActivity {
private Button Btn;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Btn=(Button)findViewById(R.id.button1);
Btn.setOnClickListener(new View.OnClickListener(){
public void onClick (View view) {
FragmentManager fm = getSupportFragmentManager();
InterDialog pruebafragment = new InterDialog();
pruebafragment.show(fm,"MyFragment");
}
});
}
public void onFinishEditDialog (String inputText) {
Toast.makeText(this, "Hi, " + inputText, Toast.LENGTH_SHORT).show();
}
}
and DialogFragment
public class InterDialog extends DialogFragment {
public interface EditNameDialogListener {
void onFinishEditDialog(String inputText);
}
public InterDialog() {
// Empty constructor required for DialogFragment
}
EditNameDialogListener activity;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.new_layout, container);
activity = (EditNameDialogListener) getActivity();
Button button = (Button)view.findViewById(R.id.Btnreturn);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
activity.onFinishEditDialog("errorrrr");
getDialog().dismiss();
}
});
return view;
}
}
The line:
activity = (EditNameDialogListener) getActivity();
is what is breaking it. Make sure your activity implements the EditNameDialogListener interface by doing
public class MainActivity extends FragmentActivity implements EditNameDialogListener {
Hope that helps