AlertDialog "onClick" method not working properly - java

I currently have an alert dialog that is being displayed on a fragment. The dialog displays to the user with no issues, but the "setPositiveButton" and "setNegativeButton" are not responding to the user interaction correctly, the Log.i after the on "setPositiveButton" is pressed is the only thing that is actually working. I want it to display a Toast message and travel to a new fragment after the possitive button is has been pressed.
private FragmentRequestCodeBinding binding;
//TAG
private static final String TAG = "requestCodeFragment";
//Values
private String firstLetter = "B";
private int secondLetter = 0;
private String thirdLetter = "0";
private String fourthLetter = "0";
private String fifthLetter = "0";
private String dtcCode = firstLetter + secondLetter + thirdLetter + fourthLetter + fifthLetter;
//Buttons
private Button request;
//Views
View root;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
binding = FragmentRequestCodeBinding.inflate(inflater, container, false);
root = binding.getRoot();
request = root.findViewById(R.id.requestButton);
// Inflate the layout for this fragment
return root;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final NavController navController = Navigation.findNavController(view);
request.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new AlertDialog.Builder(getContext())
.setIcon(R.drawable.ic_baseline_priority_high_24)
.setTitle("Request for " + dtcCode)
.setMessage("Are you sure you want to request the following code " +
"for this car model?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getContext(), "Ticket created successfully!",
Toast.LENGTH_SHORT).show();
navController.navigate(R.id.action_requestCodeFragment_to_navigation_profile);
Log.i(TAG, "onClick: Pressed");
}
})
.setNegativeButton("No", null)
.setCancelable(true)
.show();
}
});
}

Sorry to bother guys, the code is all good. I started using a real device instead of the android emulator and everything is working just fine.

Related

How can i pass data from custom dialog box to Fragment in android studio using java?

I am new to android studio and Java. I have create custom dialog box with input textbox. I want to pass data from custom dialog to fragment layout. How can I achieve that ?
I saw this post but didn't get it. Please help me out !
Passing a data from Dialog to Fragment in android
Edited
Here's my code >>
public class IncomeFragment extends Fragment{
TextView title, textRsTotal;
Dialog dialog;
int total = 0;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
title = view.findViewById(R.id.totalIncomeTitle);
Button button = view.findViewById(R.id.addIncomeBtn);
textRsTotal = view.findViewById(R.id.totalExpenseTitle);
dialog = new Dialog(getActivity());
if (getActivity() != null) {
if (!CheckInternet.isNetworkAvailable(getActivity())) {
//show no internet connection !
}
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.setContentView(R.layout.income_custom_dialog);
dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
RadioGroup radioGroup = dialog.findViewById(R.id.radioGroup);
Button buttonAdd = dialog.findViewById(R.id.addBtn);
TextInputEditText editText = dialog.findViewById(R.id.editText);
radioGroup.clearCheck();
radioGroup.animate();
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
RadioButton radioButton = (RadioButton) radioGroup.findViewById(checkedId);
}
});
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int selectedId = radioGroup.getCheckedRadioButtonId();
if (selectedId == -1) {
Toast.makeText(getActivity(), "Please select your income type", Toast.LENGTH_SHORT).show();
} else {
RadioButton radioButton = (RadioButton) radioGroup.findViewById(selectedId);
String getIncome = editText.getText().toString();
Toast.makeText(getActivity(), radioButton.getText() + " is selected & total is Rs."+ total, Toast.LENGTH_SHORT).show();
}
}
});
dialog.show();
}
});
super.onViewCreated(view, savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_income, container, false);
// Inflate the layout for this fragment
return view;
}
}
Ok, try this :
public class IncomeFragment extends Fragment {
TextView title, textRsTotal;
Dialog dialog;
int total = 0;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
title = view.findViewById(R.id.totalIncomeTitle);
Button button = view.findViewById(R.id.addIncomeBtn);
textRsTotal = view.findViewById(R.id.totalExpenseTitle);
dialog = new Dialog(getActivity());
if (getActivity() != null) {
if (!CheckInternet.isNetworkAvailable(getActivity())) {
//show no internet connection !
}
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog(new MyCallback() {
#Override
public void setText(String text) {
textRsTotal.setText(text);
}
});
}
});
super.onViewCreated(view, savedInstanceState);
}
private void showDialog(MyCallback myCallback) {
dialog.setContentView(R.layout.income_custom_dialog);
dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
RadioGroup radioGroup = dialog.findViewById(R.id.radioGroup);
Button buttonAdd = dialog.findViewById(R.id.addBtn);
TextInputEditText editText = dialog.findViewById(R.id.editText);
radioGroup.clearCheck();
radioGroup.animate();
radioGroup.setOnCheckedChangeListener((radioGroup1, checkedId) -> {
RadioButton radioButton = (RadioButton) radioGroup1.findViewById(checkedId);
});
buttonAdd.setOnClickListener(view1 -> {
int selectedId = radioGroup.getCheckedRadioButtonId();
if (selectedId == -1) {
Toast.makeText(getActivity(), "Please select your income type", Toast.LENGTH_SHORT).show();
} else {
RadioButton radioButton = (RadioButton) radioGroup.findViewById(selectedId);
String getIncome = editText.getText().toString();
myCallback.setText(getIncome);
Toast.makeText(getActivity(), radioButton.getText() + " is selected & total is Rs." + total, Toast.LENGTH_SHORT).show();
}
});
dialog.show();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_income, container, false);
return view;
}
public interface MyCallback {
void setText(String text);
}
}
There are more than one method to achieve that, the one mentioned in the url you provided is suggesting to use a simple callback to forward event and data back to the calling fragment. So the pieces you are needing are all there:
Write a callback interface: public interface Callback1{ public void onInteraction(String thingToCommunicateBack); }
In your fragment: and while building the instance of your dialog, pass an instance you've built of Callback1 to that dialog like this Callback1 mCallback = new Callback1() { public void onInteraction(String thingToCommunicateBack) { /*TODO receive data, handle and update layout*/ }; (the whole fragment could be that instance using the keyword this if you decide to implement the interface there instead, like this
class Fragment1 extends Fragment implements Callback1 and implement its method within fragment's class after the keyword override)
In your Dialog class: when the interaction (click) that should trigger the event and send data back happens, invoke callback's method like this: mCallback1.onInteraction("text from your EditText to pass")
Now, you passed some data from custom dialog back to a fragment.

Cannot use value from edittext in android fragment, where to place it?

I know it's probably very simple, but my app is not working. I need to input weight in Edittext and use its value, and the total distance value from the method CalculateDistance and the value of the CalculateCalories method.
With this code, I'm not able to click on Start Button.
Where do I have to add code which gets the value from Edittext and how can I make it work?
My code currently looks like this:
public class RunningModeFragment extends Fragment implements IGPSActivity
{
MyLocation myLocation=null;
Button btnRunningModeStart=null;
EditText txtWeight=null;
TextView txtTotalDistance=null;
TextView txtCalories=null;
Button btnShowRunningHistory = null;
String weight;
Float weightInKg;
Float caloriesBurned;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.running_mode_fragment, container, false);
}
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
txtTotalDistance=(TextView) getView().findViewById(R.id.txtTotalDistance);
txtWeight=(EditText) getView().findViewById(R.id.txtWeight);
txtCalories=(TextView) getView().findViewById(R.id.txtCalories);
if (txtWeight.getText().toString().isEmpty())
{
return;
}
else {
weight = txtWeight.getText().toString();
weightInKg = Float.parseFloat(weight);
}
btnRunningModeStart = (Button) getView().findViewById(R.id.btnRunningModeStart);
btnRunningModeStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
onClick_StartRunningMode(v);
}
});
btnShowRunningHistory = (Button) getView().findViewById(R.id.btnShowRunningHistory);
btnShowRunningHistory.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onClick_ShowRunningHistory(v);
}
});
}
private void onClick_ShowRunningHistory(View v) {
Fragment fragment = new RunningHistoryFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment, "Running History");
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.commit();
}
private void onClick_StartRunningMode(View v)
{
if(myLocation ==null)
{
new Thread(new Runnable() {
public void run() {
DatabaseFacade dbfacade = new DatabaseFacade(getView().getContext());
Activity activity = new Activity(ActivityMode.RUNNING);
activity.setActivityId(activity.getActivityId());
activity.setStart(new Timestamp(new Date().getTime()));
dbfacade.saveActivity(activity);
}
}).start();
Toast.makeText(this.getActivity(), "Start Running mode", Toast.LENGTH_SHORT).show();
myLocation = new MyLocation();
myLocation.LocationStart(this);
btnRunningModeStart.setText("Stop");
}
else
{
Toast.makeText(this.getActivity(), "Stop Running mode", Toast.LENGTH_SHORT).show();
myLocation.LocationListenerStop();
myLocation = null;
btnRunningModeStart.setText("Start");
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
}
Location lastPoint = null;
float totalDistance = 0;
public static float CalculateDistance(Location startPoint, Location endPoint)
{
return (startPoint.distanceTo(endPoint) / ((float)1000));
}
public static float CalculateCalories(float a, float b){
return ((float)1.036)*a*b;
}
#Override
public void locationChanged(Location location)
{
try
{
if(lastPoint==null)lastPoint = location;
totalDistance += CalculateDistance(lastPoint, location);
lastPoint=location;
txtTotalDistance.setText(totalDistance + " km");
caloriesBurned=CalculateCalories(totalDistance,weightInKg);
txtCalories.setText(caloriesBurned + " kcal");
DatabaseFacade dbf = new DatabaseFacade(getView().getContext());
Activity activity = new Activity(ActivityMode.RUNNING);
dbf.saveLocation(new GpsLocation(activity.getActivityId(), location.getLongitude(), location.getLatitude(), location.getAccuracy()));
}catch (Exception E)
{
E.printStackTrace();
}
}
public void onResume(){
super.onResume();
((Main) getActivity()).setActionBarTitle("Running mode");
NavigationView navigationView = (NavigationView) getActivity().findViewById(R.id.nav_view);
// navigationView.setNavigationItemSelectedListener((Main) getActivity());
navigationView.setCheckedItem(R.id.runningMode);
}
}
I need to do the following:
get the value from EditText txtWeight, parse it to float and use in CalculateCalories method
public static float CalculateCalories(float a, float b){
return ((float)1.036)*a*b;
}
I tried with this, but it's not working
if (txtWeight.getText().toString().isEmpty())
{
return;
}
else {
weight = txtWeight.getText().toString();
weightInKg = Float.parseFloat(weight);
}
first of all create a view than initialize textview inside onCreateView like this,
View view = inflater.inflate(R.layout.fg_unapproved_leave, container, false);
Textview tv= view.findViewById(R.id.tv);
the code your have written in onViewCreated() should be in onCreateVIew(). remove it from onViewCreated().
You can put it on your onCreateView() as #jitendra purohit told to you, as follows :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fg_unapproved_leave, container, false);
txtTotalDistance=(TextView) view.findViewById(R.id.txtTotalDistance);
txtWeight=(EditText) view.findViewById(R.id.txtWeight);
txtCalories=(TextView) view.findViewById(R.id.txtCalories);
...
return view;
}
Or you can keep your code in your onViewCreated() but instead of getView() you can do getActivity() something like this :
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
txtTotalDistance=(TextView) getActivity().findViewById(R.id.txtTotalDistance);
txtWeight=(EditText) getActivity().findViewById(R.id.txtWeight);
txtCalories=(TextView) getActivity().findViewById(R.id.txtCalories);
...
See this question/answers aswell...
You can do that in an onClick() or if you do want to show the changes dynamically use TextWatcher.
Using TextWatchers
TextWatcher textWatcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
if (txtWeight.getText().toString().isEmpty()) {
return;
}
else {
weight = txtWeight.getText().toString();
weightInKg = Float.parseFloat(weight);
//Call your CalculateCalories method
}
}
};
}
Using onClick I'm not going to implement it, but you can do it with a Button or on the same EditText and do the same stuff that in afterChangedText() on TextWatcher.
Remember in onCreateView() you'll have to do this :
txtWeight.addTextChangedListener(textWatcher);
Put that line ==> weight = txtWeight.getText().toString(); in the onCLick method
btnShowRunningHistory = (Button) getView().findViewById(R.id.btnShowRunningHistory);
btnShowRunningHistory.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (txtWeight.getText().toString().isEmpty())
{
return;
}
else {
weight = txtWeight.getText().toString();
weightInKg = Float.parseFloat(weight);
}
onClick_ShowRunningHistory(v);
}
});
*If you are using View binding*
Add this line under onViewCreated
val binding=<BindingFile>.bind(<binding.root from onCreate View>)
and try accessing values now using local binding variable.
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
binding = FragmentSigninBinding.inflate(layoutInflater, container, false)
val udata = "don't have a account ?"
val content = SpannableString(udata)
content.setSpan(UnderlineSpan(), 0, udata.length, 0)
binding.textView5.text = content
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val root = FragmentSigninBinding.bind(binding.root)
// Navigate to signup fragment
binding.signup.setOnClickListener {
view.findNavController().navigate(R.id.action_signin_to_signup)
}

Progress Dialog does not appear

I have a fragment that, when is pressed a button should show a Progress Dialog and execute a method that contains an AsyncTask but when I press the button, the Progess Dialog does not appear on the screen but the async task is executed. This is the code of the fragment
public class ParcheggiaFragment extends Fragment {
private Button button;
ProgressDialog progressDialog1;
SharedPreferences prefs;
HttpGetNoleggio httpGetNoleggio;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View layout = inflater.inflate(R.layout.fragment_parcheggia, container, false);
button = (Button) layout.findViewById(R.id.button);
prefs = this.getActivity().getSharedPreferences(Keys.SHARED_PREFERENCES, Context.MODE_PRIVATE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressDialog1.show();
int a = checkNoleggioCompletato();
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_principale, new ResultFragment());
fragmentTransaction.commit();
}
});
return layout;
}
private int checkNoleggioCompletato() {
final int id = prefs.getInt(Keys.ID_UTENTE, -1);
Integer[] noleggio;
int idNoleggio = -1;
try {
String str = "here i put the url that i have to use" + id;
URL url = new URL(str);
noleggio = httpGetNoleggio.execute(url).get();
idNoleggio = noleggio[0];
int idBici = noleggio[1];
int noleggioResult = idNoleggio;
} catch (MalformedURLException | ExecutionException | InterruptedException e) {
e.printStackTrace();
}
return idNoleggio;
}
#Override
public void onStart() {
progressDialog1 = new ProgressDialog(this.getActivity());
progressDialog1.setIndeterminate(true);
super.onStart();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
httpGetNoleggio = new HttpGetNoleggio(this.getActivity());
}
#Override
public void onResume() {
super.onResume();
}
}
The code seems correct and I can't understand why the ProgressDialog does not appear.
HttpNoleggio is another class that extends AsyncTask and implements the doInBackground method
As per your code you are displaying the progress bar in ParcheggiaFragment and then replacing this fragment with ResultFragment. As ResultFragment replaced ParcheggiaFragment so that progress bar is not displaying. Just comment the following code:
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_principale, new ResultFragment());
fragmentTransaction.commit();
Then, progressbar will be visible.

How to send data from DialogFragment to DialogFragment?

I have a problem with sending data from fragment to fragment. I have DialogFragment named fmonday, it is Viewpager's fragment.
I call other DialogFragment, named AlertDFragment to add some data to my fragment. I can read the data from spinner, it's working good.
Now I need to send one variable, type string, from AlertDFragment to fmonday.
Here is the code of fmonday:
public class fmonday extends DialogFragment implements LoaderManager.LoaderCallbacks<Cursor> {
DB db;
Button button12;
DialogFragment dlg1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dlg1 = new AlertDFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fmonday, container, false);
button12 = (Button) rootView.findViewById(R.id.button12);
button12.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
dlg1.show(getFragmentManager(), "dlg1");
}
});
return rootView;
}
And code of AlertDFragment:
public class AlertDFragment extends DialogFragment {
Spinner spin;
DB db;
String string1;
Button button13;
private String namestr;
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
LayoutInflater li = LayoutInflater.from(getActivity());
View fdfS = li.inflate(R.layout.fdf, null);
adb.setView(fdfS);
spin=(Spinner)fdfS.findViewById(R.id.spinner);
db = new DB(getActivity());
db.open();
spin.setOnItemSelectedListener(new OnSpinnerItemClicked());
loadSpinnerData();
button13 = (Button) fdfS.findViewById(R.id.button13);
button13.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getActivity().getApplicationContext(), "Clicked : " +
string1, Toast.LENGTH_LONG).show();
getDialog().dismiss();
}
});
return adb.create();
}
I can't find the way to send this string1 variable to my fmonday DialogFragment, because simple intent doesn't work with non-activity things. Also read some advices about bundle, but couldn't find out how to work with it.
Thanks
UPDATE
fmonday:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dlg1 = new AlertDFragment();
string1 = getArguments().getString("latitude");
}
AlertDFragment:
public class AlertDFragment extends DialogFragment {
Spinner spin;
DB db;
String string1;
Button button13;
private String namestr;
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
LayoutInflater li = LayoutInflater.from(getActivity());
View fdfS = li.inflate(R.layout.fdf, null);
adb.setView(fdfS);
spin=(Spinner)fdfS.findViewById(R.id.spinner);
db = new DB(getActivity());
db.open();
spin.setOnItemSelectedListener(new OnSpinnerItemClicked());
loadSpinnerData();
button13 = (Button) fdfS.findViewById(R.id.button13);
button13.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getActivity().getApplicationContext(), "Clicked : " +
string1, Toast.LENGTH_LONG).show();
Bundle bundle = new Bundle();
bundle.putString("latitude", string1);
fmonday alertdfragment= new fmonday();
alertdfragment.setArguments(bundle);
getDialog().dismiss();
}
});
return adb.create();
}
To Set Data:
Bundle bundle = new Bundle();
bundle.putString("latitude", latitude);
MapFragment mapFragment = new MapFragment();
mapFragment.setArguments(bundle);
To Get Data
String latitude = getArguments().getString("latitude")
You can crate a setter to your second dialogFragment ex:
public void setSmth(String value)
{
this.myData = value;
}
, than on your first dialog
DialogFragment dlg1 = new AlertDFragment();
dlg1.setSmth(your data here);
before showing the second one;

Fragment returning null from intent

So i made a bunch of 4 buttons , put an intent to each of them . They all navigate to the same Fragment class . But their extras are different, so if button1 was clicked , Fragment would open and do a certain action , if button2 was clicked , Fragment would do another action and so on. I tried the code on normal activities and it worked , but in fragments its not working . It just returns me "Id is null"
Class sending the intent
public class Intennt extends ActionBarActivity {
Button bt1,bt2,bt3,bt4;
Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intennt);
bt1 = (Button) findViewById(R.id.button);
bt2 = (Button) findViewById(R.id.button2);
bt3 = (Button) findViewById(R.id.button3);
bt4 = (Button) findViewById(R.id.button4);
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, ItemListActivity.class);
i.putExtra(ItemDetailFragment.ID_ACTION,ItemDetailFragment.ACTION_1);
startActivity(i);
}
});
bt2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, ItemListActivity.class);
i.putExtra(ItemDetailFragment.ID_ACTION,
ItemDetailFragment.ACTION_2);
startActivity(i);
}
});
}
Fragment receiving the intent and extras
public class ItemDetailFragment extends Fragment {
public static final int ACTION_1 = 1;
public static final int ACTION_2 = 2;
public static final int ACTION_3 = 3;
public static final int ACTION_4 = 4;
public static final int ACTION_NULL = -1;
public static final String ID_ACTION = "action_id";
public static final String ARG_ITEM_ID = "item_id";
private DummyContent.DummyItem mItem;
public ItemDetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments().containsKey(ARG_ITEM_ID)) {
// Load the dummy content specified by the fragment
// arguments. In a real-world scenario, use a Loader
// to load content from a content provider.
mItem =
DummyContent.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID));
}
int id = getActivity().getIntent().getIntExtra(ID_ACTION, -1);
if (id == ACTION_NULL) {
Log.d("TAG", "id is null");
Toast.makeText(getActivity(), "id is null!",
Toast.LENGTH_SHORT).show();
} else if (id == ACTION_1) {
Log.i("TAG", "ALLOHA! from button 1");
Toast.makeText(getActivity(), "Aloha from button 1!",
Toast.LENGTH_LONG).show();
} else if (id == ACTION_2) {
Log.i("TAG", "Hello from button 2");
Toast.makeText(getActivity(),"Hello from button 2!",
Toast.LENGTH_LONG).show();
}
else if (id == ACTION_3) {
Log.i("TAG", "Hello from button 3");
Toast.makeText(getActivity(),"Hello from button 2!",
Toast.LENGTH_LONG).show();
}
else if (id == ACTION_4) {
Log.i("TAG", "Hello from button 4");
Toast.makeText(getActivity(),"Hello from button 2!",
Toast.LENGTH_LONG).show();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_item_detail,
container, false);
return rootView;
}
}
To navigate to a fragment, you need to instantiate the fragment class then use the FragmentManager to proceed to a transaction :
FragmentClass fragment = new FragmentClass();
getFragmentManager()
.beginTransaction()
.replace(R.id.your_fragment_view, fragment)
.commit();
You can proceed to every action right in the current activity (as it stays the main activity).
public class Questions extends DialogFragment {
private static Button Submit;
public int count = 0;
public interface DialogListener {
void onQuestionsFinish(ArrayList<xmlQuestion> l);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_questions, container, false);
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
//getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Submit = (Button) rootView.findViewById(R.id.SubmitButton);
Submit.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0){
for(int i = 0; i<questionList.size(); i++)
{
questionList.get(i).setAnswer();
}
DialogListener activity = (DialogListener) getActivity();
activity.onQuestionsFinish(questionList);
Questions.this.dismiss();
}
});
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
yInch = metrics.ydpi;
pixHeight = metrics.heightPixels;
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point(); display.getSize(size);
screenWidth=size.x; screenHeight=size.y;
LinearLayout.LayoutParams bodyParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,screenHeight*900/1024);
BodyLayout.setLayoutParams(bodyParams);
WindowManager.LayoutParams wmlp = getDialog().getWindow().getAttributes();
wmlp.height=screenHeight; wmlp.width=screenWidth;
getDialog().getWindow().setAttributes(wmlp);
WindowManager.LayoutParams lp = getDialog().getWindow().getAttributes();
lp.dimAmount=0.4f;
getDialog().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
getDialog().setCanceledOnTouchOutside(true);
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NO_FRAME, android.support.v7.appcompat.R.style.Theme_AppCompat_Light);
}
public Questions()
{
}
}
You don't have to use intents to start fragments. My main benefit for using fragments is being able to reference the data in each one much easier. You can simply create a new instance of your fragment class, and assign it's public variables. Then start it like so...
Questions q = new Questions();
q.count = 0;
q.show(getSupportFragmentManager(), "Dialog Fragment");

Categories

Resources