Can anyone tell me why this is not working? I have no errors at all but simply doesnt work.
This actually used to work fine until I added the ScreenSwipe, now I cant figure out whats wrong.
Thanks
package com.sample.sample
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
public class PageOneFragment extends Fragment {
ImageButton btn1;
static int i = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.page1_layout, container, false);
btn1 = (ImageButton) rootView.findViewById(R.id.m1_btn);
return rootView;
}
public void setupPlayPauseButton1(View view) {
btn1 = (ImageButton) view.findViewById(R.id.m1_btn);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i +=1;
if (i % 2 == 0) {
btn1.setImageResource(R.drawable.pause);
} else {
btn1.setImageResource(R.drawable.play);
}
}
});
}
}
EDIT
Is this right?
package com.wepromoteme.brapp;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
public class PageOneFragment extends Fragment {
ImageButton btn1;
int i = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.page1_layout, container, false);
btn1 = (ImageButton) rootView.findViewById(R.id.m1_btn);
setupPlayPauseButton1(rootView);
return rootView;
}
private void setupPlayPauseButton1(View view) {
btn1 = (ImageButton) view.findViewById(R.id.m1_btn);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
i +=1;
if (i % 2 == 0) {
btn1.setImageResource(R.drawable.pause);
} else {
btn1.setImageResource(R.drawable.play);
}
}
});
}
}
You did not tell what "doesn't work", but I am willing to guess this is the cause: static int i = 0;
static here means that the value of i is shared by all instances of PageOneFragment.
If you are using static to keep the variable value when the screen is rotated, etc., you should use the fragment onSaveInstanceState() method instead. You can find more information about this on the official documentation:
Handling the Fragment Lifecycle
As it happens I have figured it out, I decided to let my brain have a few hours to rest as I think I got into a downward spiral of not being able to see that wood for the trees :P
Here is my code for anyone else who stumbles on the same problems I have. This actually works:
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
public class PageTwoFragment extends Fragment {
int i = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.page2_layout, container, false);
final ImageButton btn1 = (ImageButton) rootView.findViewById(R.id.m1_btn);
final ImageButton btn2 = (ImageButton) rootView.findViewById(R.id.m2_btn);
final ImageButton btn3 = (ImageButton) rootView.findViewById(R.id.m3_btn);
final ImageButton btn4 = (ImageButton) rootView.findViewById(R.id.m4_btn);
final ImageButton btn5 = (ImageButton) rootView.findViewById(R.id.m5_btn);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i +=1;
if (i % 2 == 0) {
btn1.setImageResource(R.drawable.pause);
} else {
btn1.setImageResource(R.drawable.play);
}
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i +=1;
if (i % 2 == 0) {
btn2.setImageResource(R.drawable.pause);
} else {
btn2.setImageResource(R.drawable.play);
}
}
});
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i +=1;
if (i % 2 == 0) {
btn3.setImageResource(R.drawable.pause);
} else {
btn3.setImageResource(R.drawable.play);
}
}
});
btn4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i +=1;
if (i % 2 == 0) {
btn4.setImageResource(R.drawable.pause);
} else {
btn4.setImageResource(R.drawable.play);
}
}
});
btn5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i +=1;
if (i % 2 == 0) {
btn5.setImageResource(R.drawable.pause);
} else {
btn5.setImageResource(R.drawable.play);
}
}
});
return rootView;
}
}
Related
This question already has answers here:
Multiple Buttons' OnClickListener() android
(11 answers)
Closed 2 years ago.
As you can see in my code below, today I need to create for each checkbox a setOnClickListener,
but I'd like to make only one and set this method for all my checkboxes, this way, I could simplify my code. With an activity, I was able to do that as you can see in the second code example:
Take a look at my code first code:
package com.example.cursobaralhocigano.ui.deck;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.example.cursobaralhocigano.MainActivity;
import com.example.cursobaralhocigano.R;
import com.example.cursobaralhocigano.dao.BancoDeDados;
import com.example.cursobaralhocigano.classes.cBaralhos;
import com.example.cursobaralhocigano.dao.uLibSql;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
/**
* A simple {#link Fragment} subclass.
*/
public class DeckFragment extends Fragment {
private uLibSql DB;
private cBaralhos baralho = new cBaralhos();
CheckBox ck01, ck02, ck03, ck04, ck05;
ImageButton Img;
public DeckFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
LinearLayout ln;
View view = inflater.inflate(R.layout.fragment_deck, container, false);
final FloatingActionButton fab = ((MainActivity) getActivity()).findViewById(R.id.fab);
if (fab.isShown()) {
fab.hide();
}
DB = new uLibSql(getActivity());
int _baralho = DB.PegaBaralhoSelecionada();
ck01 = view.findViewById(R.id.ck01);
ck02 = view.findViewById(R.id.ck02);
ck03 = view.findViewById(R.id.ck03);
ck04 = view.findViewById(R.id.ck04);
ck05 = view.findViewById(R.id.ck05);
LimpaChecks();
ck01.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LimpaChecks();
ck01.setChecked(true);
DB.GravaBaralhoSelecionada(ck01.getTag().toString());
}
});
ck02.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LimpaChecks();
ck02.setChecked(true);
DB.GravaBaralhoSelecionada(ck02.getTag().toString());
}
});
ck03.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LimpaChecks();
ck03.setChecked(true);
DB.GravaBaralhoSelecionada(ck03.getTag().toString());
}
});
ck04.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LimpaChecks();
ck04.setChecked(true);
DB.GravaBaralhoSelecionada(ck04.getTag().toString());
}
});
ck05.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LimpaChecks();
ck05.setChecked(true);
DB.GravaBaralhoSelecionada(ck05.getTag().toString());
}
});
if (_baralho == 1) {
ck01.setChecked(true);
}
if (_baralho == 2) {
ck02.setChecked(true);
}
if (_baralho == 3) {
ck03.setChecked(true);
}
if (_baralho == 4) {
ck04.setChecked(true);
}
if (_baralho == 5) {
ck05.setChecked(true);
}
ln = view.findViewById(R.id.LinearFilho01);
MostraCartas(1, ln);
ln = view.findViewById(R.id.LinearFilho02);
MostraCartas(2, ln);
ln = view.findViewById(R.id.LinearFilho03);
MostraCartas(3, ln);
ln = view.findViewById(R.id.LinearFilho04);
MostraCartas(4, ln);
ln = view.findViewById(R.id.LinearFilho05);
MostraCartas(5, ln);
return view;
}
public void LimpaChecks() {
ck01.setChecked(false);
ck02.setChecked(false);
ck03.setChecked(false);
ck04.setChecked(false);
}
public void MostraCartas(int _baralho, LinearLayout ln) {
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(300, 400, 1);
for (int i = 1; i <= 36; i++) {
Img = new ImageButton(getActivity());
Img.setId(View.generateViewId());
Img.setLayoutParams(param);
Img.setImageResource(baralho.pegaIdcarta(i, _baralho));
Img.setScaleType(ImageView.ScaleType.FIT_CENTER);
Img.setTag(i);
//Img.setOnClickListener(PegaCk(ck));
ln.addView(Img);
}
}
}
My second example that works fine in an activity
package com.example.cursodebaralho;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.example.cursodebaralho.dao.BancoDeDados;
import com.example.cursodebaralho.modelo.cCartas;
public class EscolhaCarta extends AppCompatActivity {
private BancoDeDados DB;
cCartas carta = new cCartas();
CheckBox ck01, ck02, ck03, ck04;
LinearLayout ln01;
ImageButton Img;
int baralho = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_escolha_carta);
Toolbar toolbar = findViewById(R.id.toolbar2);
setSupportActionBar(toolbar);
toolbar.setTitle("Curso de Baralho Cigano");
toolbar.setSubtitle("Escolhendo o Baralho de Estudo");
MostraCartas01();
MostraCartas02();
MostraCartas03();
MostraCartas04();
DB = new BancoDeDados(this);
baralho = DB.PegaBaralhoSelecionada();
ck01 = findViewById(R.id.ck01);
ck02 = findViewById(R.id.ck02);
ck03 = findViewById(R.id.ck03);
ck04 = findViewById(R.id.ck04);
if (baralho == 1) {
ck01.setChecked(true);
}
if (baralho == 2) {
ck02.setChecked(true);
}
if (baralho == 3) {
ck03.setChecked(true);
}
if (baralho == 4) {
ck04.setChecked(true);
}
ck01.setOnClickListener(PegaCk(ck01));
ck02.setOnClickListener(PegaCk(ck02));
ck03.setOnClickListener(PegaCk(ck03));
ck04.setOnClickListener(PegaCk(ck04));
/*
https://thoughtbot.com/blog/android-imageview-scaletype-a-visual-guide
https://stackoverflow.com/questions/10123830/android-imageview-scaletype-and-item-height
*/
}
View.OnClickListener PegaCk(final CheckBox ck) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
LimpaChecks();
ck.setChecked(true);
DB.GravaBaralhoSelecionada(ck.getTag().toString());
}
};
}
public void LimpaChecks() {
ck01.setChecked(false);
ck02.setChecked(false);
ck03.setChecked(false);
ck04.setChecked(false);
}
public void MostraCartas01() {
ln01 = findViewById(R.id.Linear01);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(300, 400, 1);
for (int i = 1; i <= 36; i++) {
Img = new ImageButton(this);
Img.setId(View.generateViewId());
Img.setLayoutParams(param);
Img.setImageResource(carta.pegaIdcarta(i, 1));
Img.setScaleType(ImageView.ScaleType.FIT_START);
Img.setTag(i);
//Img.setOnClickListener(PegaCk(ck));
ln01.addView(Img);
}
}
public void MostraCartas02() {
ln01 = findViewById(R.id.Linear02);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(300, 400, 1);
for (int i = 1; i <= 36; i++) {
Img = new ImageButton(this);
Img.setId(View.generateViewId());
Img.setLayoutParams(param);
Img.setImageResource(carta.pegaIdcarta(i, 2));
Img.setScaleType(ImageView.ScaleType.FIT_START);
Img.setTag(i);
//Img.setOnClickListener(PegaCk(ck));
ln01.addView(Img);
}
}
public void MostraCartas03() {
ln01 = findViewById(R.id.Linear03);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(300, 400, 1);
for (int i = 1; i <= 36; i++) {
Img = new ImageButton(this);
Img.setId(View.generateViewId());
Img.setLayoutParams(param);
Img.setImageResource(carta.pegaIdcarta(i, 3));
Img.setScaleType(ImageView.ScaleType.FIT_START);
Img.setTag(i);
//Img.setOnClickListener(PegaCk(ck));
ln01.addView(Img);
}
}
public void MostraCartas04() {
ln01 = findViewById(R.id.Linear04);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(300, 400, 1);
for (int i = 1; i <= 36; i++) {
Img = new ImageButton(this);
Img.setId(View.generateViewId());
Img.setLayoutParams(param);
Img.setImageResource(carta.pegaIdcarta(i, 4));
Img.setScaleType(ImageView.ScaleType.FIT_START);
Img.setTag(i);
//Img.setOnClickListener(PegaCk(ck));
ln01.addView(Img);
}
}
}
I thanks a lot for a help
Alexandre
You can do something like this :
public class DeckFragment extends Fragment implements OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
LinearLayout ln;
View view = inflater.inflate(R.layout.fragment_deck, container, false);
ArrayList<View> checkboxes = new ArrayList<View>();
checkboxes.add(view.findViewById(R.id.ck01));
checkboxes.add(view.findViewById(R.id.ck02));
checkboxes.add(view.findViewById(R.id.ck03));
checkboxes.add(view.findViewById(R.id.ck04));
checkboxes.add(view.findViewById(R.id.ck05));
for(View v : checkboxes) {
v.setOnClickListener(this);
}
}
#Override
public void onClick(View v) {
LimpaChecks();
((CheckBox)v).setChecked(true);
DB.GravaBaralhoSelecionada(v.getTag().toString());
}
}
I am trying to maintain the ui changes so that when restarting the activity, the instance of my fragment become used with the changes of the buttons. So I found setRetainInstance(true) doesn't destroy the fragment object, however, the resulted view is destroyed. So I overrode onSaveInstance in the fragment class to save the ids of the resources that is called in the event handlers for setting it the next time the activity is created. The result was unexpected, at least for me:
1. The view of the fragment is destroyed when recreating the activity and the fragments instance become reattached to the new activity instance.
2. Event handlers become non-operational, so I don't know where is the problem.
Here is the code of the activity class:
package com.voicenoteinc.ticatactoy;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
Tic_Fragment s;
FragmentManager manager;
String TAG_FRAGMENT = "tag_fragment";
FragmentTransaction trans;
boolean retained = true;
String COLOR_ARRAY;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
manager = getFragmentManager();
s = (Tic_Fragment) manager.findFragmentByTag(TAG_FRAGMENT);
if(s == null){
s = new Tic_Fragment();
retained = false;
trans = manager.beginTransaction();
trans.add(R.id.fragment_container,s,TAG_FRAGMENT).commit();
}
}
}
and Here is the code for the Fragment class:
package com.voicenoteinc.ticatactoy;
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Switch;
public class Tic_Fragment extends Fragment {
public Button bu1,bu2,bu3,bu4,bu5,bu6,bu7,bu8,bu9;
int COLOR[] = new int[9];
public String COLOR_KEY = "COLOR_KEY";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
for(int i =0; i<9;i++){
COLOR[i] = R.color.granite;
}
return inflater.inflate(R.layout.tic_fragment,container,false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
for(int i =0; i<9;i++){
COLOR[i] = R.color.granite;
}
super.onViewCreated(view, savedInstanceState);
if(savedInstanceState!=null){
COLOR=savedInstanceState.getIntArray(COLOR_KEY);
bu1.setBackgroundResource(COLOR[0]);
bu2.setBackgroundResource(COLOR[1]);
bu3.setBackgroundResource(COLOR[2]);
bu4.setBackgroundResource(COLOR[3]);
bu5.setBackgroundResource(COLOR[4]);
bu6.setBackgroundResource(COLOR[5]);
bu7.setBackgroundResource(COLOR[6]);
bu8.setBackgroundResource(COLOR[7]);
bu9.setBackgroundResource(COLOR[8]);
}else{
bu1 = getView().findViewById(R.id.bu1);
bu2 = getView().findViewById(R.id.bu2);
bu3 = getView().findViewById(R.id.bu3);
bu4 = getView().findViewById(R.id.bu4);
bu5 = getView().findViewById(R.id.bu5);
bu6 = getView().findViewById(R.id.bu6);
bu7 = getView().findViewById(R.id.bu7);
bu8 = getView().findViewById(R.id.bu8);
bu9 = getView().findViewById(R.id.bu9);
}
eventhandlers();
}
public void eventhandlers(){
bu1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display(bu1,1);
}
});
bu2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display(bu2,2);
}
});
bu3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display(bu3,3);
}
});
bu4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display(bu4,4);
}
});
bu5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display(bu5,5);
}
});
bu6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display(bu6,6);
}
});
bu7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display(bu7,7);
}
});
bu8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display(bu8,8);
}
});
bu9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display(bu9,9);
}
});
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putIntArray(COLOR_KEY,COLOR);
}
public void display(Button bu, int i){
int backgroundColor = R.color.greenery;
bu.setBackgroundResource(backgroundColor);
COLOR[i-1] = backgroundColor;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
}
Thank ou for helping, and by the way I am new to using Fragments and Dynamic Layouts
I am new to android development and I am trying to pass a Boolean value from dialog fragment to the activity.
the boolean value is supposed to be decided by the user(depends on which button user clicked). However, the boolean immediately turned to false without clicking any button.
I have tried various method recommended I found on internet but none of them works for me(I guess I have some part screwed up...), these method include:
-broadcasting
-implementing interface
-intent.putExtra
and below is the code that I have came up with, could anyone help me take a look? Any help is appreciated.
Stage:
package com.example.fuj.valorsafeworldbytrade;
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import static com.example.fuj.valorsafeworldbytrade.LosingDialogFragment.LOSING_FRAGMENT;
public class Stage extends AppCompatActivity {
String stage;
FragmentManager fragmentManager = getSupportFragmentManager();
LosingDialogFragment losingDialogFragment = new LosingDialogFragment();
BasicInfo basicInfo = new BasicInfo();
public void setText(){
TextView cpuReputation = (TextView) findViewById(R.id.cpu_reputation);
TextView cpuGold = (TextView) findViewById(R.id.cpu_gold);
TextView pGoldText = (TextView) findViewById(R.id.player_gold);
TextView pRepText = (TextView) findViewById(R.id.player_reputation);
cpuReputation.setText(String.valueOf(basicInfo.cRep));
cpuGold.setText(String.valueOf(basicInfo.cGold));
pGoldText.setText(String.valueOf(basicInfo.pGold));
pRepText.setText(String.valueOf(basicInfo.pRep));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stage);
setText();
}
protected void onStart() {
super.onStart();
stage = getIntent().getStringExtra(StageChoosingMenu.STAGE);
}
public void playerChoice(View view) {
boolean deceiveEnabled;
switch (view.getId()) {
case R.id.cooperate_button:
deceiveEnabled = false;
break;
case R.id.deceive_button:
deceiveEnabled = true;
break;
default:
throw new RuntimeException("Unknown Button ID");
}
switch (stage){
case "xumo":
xuMo(deceiveEnabled);
break;
}
}
public void xuMo(boolean playerDeceiveEnabled){
boolean cpuDeceiveEnabled;
cpuDeceiveEnabled = (Math.random() - basicInfo.faith > 0);
if (cpuDeceiveEnabled){
if (playerDeceiveEnabled){
basicInfo.playerDvsCpuD();
// faith changes to be amend w/ proper value, need record on the change of status
}
if (!playerDeceiveEnabled){
basicInfo.playerCvsCpuD();
}
}
if (!cpuDeceiveEnabled){
if (playerDeceiveEnabled){
basicInfo.playerDvsCpuC();
}
if (!playerDeceiveEnabled){
basicInfo.playerCvsCpuC();
}
}
if(basicInfo.pGold <= 0 || basicInfo.cGold <= 0 || basicInfo.pRep <= 0 || basicInfo.cRep <= 0){
//to be changed
setText();
losingDialogFragment.show(fragmentManager,LOSING_FRAGMENT);
//trying to show a alert dialog fragment
Log.d("True", String.valueOf(losingDialogFragment.tryAgainEnabled));
if(losingDialogFragment.tryAgainEnabled){//tryAgainEnabled is always false
//This is the part that I wanted to retrieve data from the user(if they want to try again or not)
basicInfo.reset();
losingDialogFragment.dismiss();
}else{
losingDialogFragment.dismiss();
}
}
setText();
// to be changed
}
}
LosingDialogFragment:
package com.example.fuj.valorsafeworldbytrade;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
/**
* Created by fuj on 20/1/2017.
*/
public class LosingDialogFragment extends DialogFragment{
public static final String LOSING_FRAGMENT = "LOSING";
public boolean tryAgainEnabled;
Intent intent = new Intent();
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_lose, container, false);;
//the following code is used to set the boolean value after the user click the button
final Button tryAgainButton = (Button)rootView.findViewById(R.id.try_again_button);
tryAgainButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tryAgainEnabled = true;
}
});
Button giveUpButton =(Button)rootView.findViewById(R.id.give_up_button);
giveUpButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tryAgainEnabled = false;
}
});
getDialog().setTitle(LOSING_FRAGMENT);
return rootView;
}
}
I am also sorry that I am not the best with English, if any things is not clear or not polite because of my poor English, please kindly let me know. I apologize in advance for any mistakes I have made.
It's because you check the value of tryAgainEnabled exactly right after showing the Dialog. Dialog starts Asynchronously, It means that it starts in diffrent Thread and your current thread doesn't wait for dismissing Dialog, So this line of your code if(losingDialogFragment.tryAgainEnabled){ runs exactly after you show dialog, befor you set value to tryAgainEnabled. Because the default value of boolean is always false, you will get false everytime.
I suggest that use listener for this:
Dialog:
public class LosingDialogFragment extends DialogFragment {
public static final String LOSING_FRAGMENT = "LOSING";
public boolean tryAgainEnabled;
Intent intent = new Intent();
private View.OnClickListener onTryAgainButtonClickLisnter;
private View.OnClickListener onGiveUpButtonClickLisnter;
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_lose, container, false);;
final Button tryAgainButton = (Button)rootView.findViewById(R.id.try_again_button);
tryAgainButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(onTryAgainButtonClickLisnter!=null)
onTryAgainButtonClickLisnter.onClick(v);
}
});
Button giveUpButton =(Button)rootView.findViewById(R.id.give_up_button);
giveUpButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(onGiveUpButtonClickLisnter!=null)
onGiveUpButtonClickLisnter.onClick(v);
}
});
getDialog().setTitle(LOSING_FRAGMENT);
return rootView;
}
public void setOnTryAgainButtonClickLisnter(View.OnClickListener onTryAgainButtonClickLisnter) {
this.onTryAgainButtonClickLisnter = onTryAgainButtonClickLisnter;
}
public void setOnGiveUpButtonClickLisnter(View.OnClickListener onGiveUpButtonClickLisnter) {
this.onGiveUpButtonClickLisnter = onGiveUpButtonClickLisnter;
}
}
In your activity call dialog like this:
LosingDialogFragment losingDialogFragment = new LosingDialogFragment();
losingDialogFragment.setOnTryAgainButtonClickLisnter(new View.OnClickListener() {
#Override
public void onClick(View v) {
tryAgain();
losingDialogFragment.dismiss();
}
});
losingDialogFragment.setOnGiveUpButtonClickLisnter(new View.OnClickListener() {
#Override
public void onClick(View v) {
giveUp();
losingDialogFragment.dismiss();
}
});
losingDialogFragment.show(fragmentManager, "");
Declare public boolean tryAgainEnabled; in your Stage Activity and youd can update that variable using ((Stage)context).tryAgainEnabled.
package com.example.fuj.valorsafeworldbytrade;
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import static com.example.fuj.valorsafeworldbytrade.LosingDialogFragment.LOSING_FRAGMENT;
public class Stage extends AppCompatActivity {
String stage;
FragmentManager fragmentManager = getSupportFragmentManager();
LosingDialogFragment losingDialogFragment = new LosingDialogFragment();
BasicInfo basicInfo = new BasicInfo();
public boolean tryAgainEnabled;
public void setText(){
TextView cpuReputation = (TextView) findViewById(R.id.cpu_reputation);
TextView cpuGold = (TextView) findViewById(R.id.cpu_gold);
TextView pGoldText = (TextView) findViewById(R.id.player_gold);
TextView pRepText = (TextView) findViewById(R.id.player_reputation);
cpuReputation.setText(String.valueOf(basicInfo.cRep));
cpuGold.setText(String.valueOf(basicInfo.cGold));
pGoldText.setText(String.valueOf(basicInfo.pGold));
pRepText.setText(String.valueOf(basicInfo.pRep));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stage);
setText();
}
protected void onStart() {
super.onStart();
stage = getIntent().getStringExtra(StageChoosingMenu.STAGE);
}
public void playerChoice(View view) {
boolean deceiveEnabled;
switch (view.getId()) {
case R.id.cooperate_button:
deceiveEnabled = false;
break;
case R.id.deceive_button:
deceiveEnabled = true;
break;
default:
throw new RuntimeException("Unknown Button ID");
}
switch (stage){
case "xumo":
xuMo(deceiveEnabled);
break;
}
}
public void xuMo(boolean playerDeceiveEnabled){
boolean cpuDeceiveEnabled;
cpuDeceiveEnabled = (Math.random() - basicInfo.faith > 0);
if (cpuDeceiveEnabled){
if (playerDeceiveEnabled){
basicInfo.playerDvsCpuD();
// faith changes to be amend w/ proper value, need record on the change of status
}
if (!playerDeceiveEnabled){
basicInfo.playerCvsCpuD();
}
}
if (!cpuDeceiveEnabled){
if (playerDeceiveEnabled){
basicInfo.playerDvsCpuC();
}
if (!playerDeceiveEnabled){
basicInfo.playerCvsCpuC();
}
}
if(basicInfo.pGold <= 0 || basicInfo.cGold <= 0 || basicInfo.pRep <= 0 || basicInfo.cRep <= 0){
//to be changed
setText();
losingDialogFragment.show(fragmentManager,LOSING_FRAGMENT);
Log.d("True", String.valueOf(losingDialogFragment.tryAgainEnabled));
if(losingDialogFragment.tryAgainEnabled){//tryAgainEnabled is always false
basicInfo.reset();
losingDialogFragment.dismiss();
}else{
losingDialogFragment.dismiss();
}
}
setText();
// to be changed
}
}
And in Fragment
package com.example.fuj.valorsafeworldbytrade;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
/**
* Created by fuj on 20/1/2017.
*/
public class LosingDialogFragment extends DialogFragment{
public static final String LOSING_FRAGMENT = "LOSING";
Context context;
Intent intent = new Intent();
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_lose, container, false);;
final Button tryAgainButton = (Button)rootView.findViewById(R.id.try_again_button);
tryAgainButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((Stage)context).tryAgainEnabled = true;
}
});
Button giveUpButton =(Button)rootView.findViewById(R.id.give_up_button);
giveUpButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((Stage)context).tryAgainEnabled = false;
}
});
getDialog().setTitle(LOSING_FRAGMENT);
return rootView;
}
}
I know there are some other answers out there and I have tried them all and cannot get it to work. I need to save the two pieces of output data "brereton" and "hoppus". I think my coding can be done much better but I am real new to this so donĀ“t judge harshly... thankyou in advance for any help.
package com.example.dpivl.teak101;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Tab1 extends Fragment {
EditText num1;
EditText num2;
EditText num3;
TextView brereton;
TextView hoppus;
Button calculate;
Button reset;
double w = 0;
double x = 0;
double y = 0;
double z = 0;
double h = 0;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab_1, container, false);
return v;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initControls();
}
private void initControls() {
num1 = (EditText) getView().findViewById(R.id.editTextHeight);
num2 = (EditText) getView().findViewById(R.id.editTextWidth);
num3 = (EditText) getView().findViewById(R.id.editTextAmount);
brereton = (TextView) getView().findViewById(R.id.answerBrereton);
hoppus = (TextView) getView().findViewById(R.id.answerHoppus);
calculate = (Button) getView().findViewById(R.id.buttonCalc);
reset = (Button) getView().findViewById(R.id.reset);
reset.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
reset();
}
});
calculate.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
if (num1.getText().toString().equals("")|| num2.getText().toString().equals("")|| num3.getText().toString().equals("")){
Toast.makeText(getActivity(),"Insert Measurements!",Toast.LENGTH_SHORT).show();
}
else {
calculate();
}
}
});
}
private void calculate() {
w = Double.parseDouble(num1.getText().toString());
x = Double.parseDouble(num2.getText().toString());
y = Double.parseDouble(num3.getText().toString());
z = (x / 314) * (x / 314) * w * y;
h = z * 0.7852;
brereton.setText(Double.toString(z));
hoppus.setText(Double.toString(h));
}
private void reset() {
num1.setText("");
num2.setText("");
num3.setText("");
brereton.setText("");
hoppus.setText("");
}
}
Save the text of your textviews in a bundle like this :
#Override
public void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
outState.putString("brereton", brereton.getText().toString());
outState.putString("hoppus", hoppus.getText().toString());
super.onSaveInstanceState(outState);
}
Now, when the activity is rotated, fragment would be recreated, and UI components would be re-inflated into the view hierarchy. After the initialization is complete (as you're doing in onActivityCreated callback), you can use the bundle in the callback, to set text to your textviews.
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
initControls();
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
brereton.setText(savedInstanceState.getString("brereton"));
hoppus.setText(savedInstanceState.getString("hoppus"));
}
}
Hope this helps.
I've looked everywhere, but I can't find what I'm looking for.
I'm trying to make a stopwatch app for android using a Chronometer inside of a Fragment, but I'm getting errors on the setOnClickListener for some buttons.
It's the variables inside of parentheses "()" fx. (mStartListener), I get the error mStartListener cannot be resolved to a variable.
please help me, I really wanna get into android developing. Thank you
Here's the code
b = (Button) getView().findViewById(R.id.start);
b.setOnClickListener(mStartListener); //--- error
b = (Button) getView().findViewById(R.id.stop);
b.setOnClickListener(mStopListener); //--- error
b = (Button) getView().findViewById(R.id.reset);
b.setOnClickListener(mResetListener); //--- error
Full Code:
import android.app.Fragment;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Chronometer;
public class StopWatchFragment extends Fragment {
Chronometer mChronometer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.stopwatch, container, false);
Button b;
mChronometer = (Chronometer) getView().findViewById(R.id.chronometer);
// Watch for button clicks.
b = (Button) getView().findViewById(R.id.start);
b.setOnClickListener(mStartListener); //--- error
b = (Button) getView().findViewById(R.id.stop);
b.setOnClickListener(mStopListener); //--- error
b = (Button) getView().findViewById(R.id.reset);
b.setOnClickListener(mResetListener); //--- error
return view;
View.OnClickListener mStartListener = new OnClickListener() {
public void onClick(View v) {
mChronometer.start();
}
};
View.OnClickListener mStopListener = new OnClickListener() {
public void onClick(View v) {
mChronometer.stop();
}
};
View.OnClickListener mResetListener = new OnClickListener() {
public void onClick(View v) {
mChronometer.setBase(SystemClock.elapsedRealtime());
}
};
}
}
Move where you declare each Listener to be class variables:
public class StopWatchFragment extends Fragment {
Chronometer mChronometer;
View.OnClickListener mStartListener;
...
Or just declare your listeners before you try to use them:
Button b;
mChronometer = (Chronometer) getView().findViewById(R.id.chronometer);
View.OnClickListener mStartListener = new OnClickListener() {
public void onClick(View v) {
mChronometer.start();
}
};
...
// Watch for button clicks.
b = (Button) getView().findViewById(R.id.start);
b.setOnClickListener(mStartListener); //--- no more error
You are defining and initializing the mStopListener inside the onCreateView method, AFTER you try to set them as the OnClickListener.
You should either move them to the start of your method:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.stopwatch, container, false);
View.OnClickListener mStartListener = new OnClickListener() {
public void onClick(View v) {
mChronometer.start();
}
};
View.OnClickListener mStopListener = new OnClickListener() {
public void onClick(View v) {
mChronometer.stop();
}
};
View.OnClickListener mResetListener = new OnClickListener() {
public void onClick(View v) {
mChronometer.setBase(SystemClock.elapsedRealtime());
}
};
Button b;
mChronometer = (Chronometer) getView().findViewById(R.id.chronometer);
// Watch for button clicks.
b = (Button) getView().findViewById(R.id.start);
b.setOnClickListener(mStartListener); //--- error
b = (Button) getView().findViewById(R.id.stop);
b.setOnClickListener(mStopListener); //--- error
b = (Button) getView().findViewById(R.id.reset);
b.setOnClickListener(mResetListener); //--- error
return view;
}
Or, put them outside your method as global variables.