Transfering class from an activity to fragment - android

Im trying to use viewPager so I want to change my class from an activity to fragment, but Im getting alot of errors, so can you tell me whats wrong and what I need to do?
Here is my original activity :
package com.pickapp.pachu.pickapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.content.Intent;
import java.util.Random;
public class MainScreen extends Activity implements OnClickListener {
private TitlesDB titles;
private Button getPickUpLine;
private TextView pickUpLine;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
titles = new TitlesDB(this);
initDB();
initialize();
}
public void initialize() {
this.getPickUpLine = (Button) findViewById(R.id.bGetLine);
this.getPickUpLine.setOnClickListener(this);
this.pickUpLine = (TextView) findViewById(R.id.tvLine);
this.pickUpLine.setOnClickListener(this);
}
public void initDB() {
titles.open();
if (!this.titles.isExist()) {
titles.createEntry("The I \n Have Cancer");
titles.createEntry("The Ocean");
}
titles.close();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bGetLine:
titles.open();
Random rnd = new Random();
int index = rnd.nextInt(titles.getLength()) + 1;
pickUpLine.setText(titles.getTitleById(index));
titles.close();
break;
case R.id.tvLine:
if(!pickUpLine.getText().toString().equals(""))
{
Intent intent = new Intent(this, PickAppLine.class);
intent.putExtra("key", pickUpLine.getText().toString());
startActivity(intent);
}
break;
}
}
}
Here is what I tried :
package com.pickapp.pachu.pickapp;
import android.os.Bundle;
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.TextView;
/**
* Created by Golan on 19/08/2014.
*/
public class MainScreenFragment extends Fragment implements OnClickListener{
private TitlesDB titles;
private Button getPickUpLine;
private TextView pickUpLine;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
titles = new TitlesDB(getActivity());
initDB();
View v = getView();
initialize(v);
return inflater.inflate(R.layout.activity_main_screen, container, false);
}
public void initialize(View v) {
this.getPickUpLine = (Button) v.findViewById(R.id.bGetLine);
this.getPickUpLine.setOnClickListener(this);
this.pickUpLine = (TextView) v.findViewById(R.id.tvLine);
this.pickUpLine.setOnClickListener(this);
}
public void initDB() {
titles.open();
if (!this.titles.isExist()) {
titles.createEntry("The I \n Have Cancer");
titles.createEntry("The Ocean");
}
titles.close();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bGetLine:
titles.open();
Random rnd = new Random();
int index = rnd.nextInt(titles.getLength()) + 1;
pickUpLine.setText(titles.getTitleById(index));
titles.close();
break;
case R.id.tvLine:
if(!pickUpLine.getText().toString().equals(""))
{
Intent intent = new Intent(this, PickAppLine.class);
intent.putExtra("key", pickUpLine.getText().toString());
startActivity(intent);
}
break;
}
}
}

We won't just fix all your code. You have to do that yourself! Remove everything that you don't need at the beginning and start adding one after the other again. Fix all the errors on the way. It is hard to know what the actual problem is when everything is wrong.
One thing that I see right away that definitely does not work is this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_main_screen, container, false); // NO, NO, NO!!
titles = new TitlesDB(getActivity());
initDB();
initialize();
}
You have a return statement in the method BEFORE you have more code. That can not work. The return statement has to be at the end!

Related

How to open a Fragment on click from a fragment in Android

Firstly I'm new to android and sorry for my english.
I have an application where I display images, in it I use a grid with image gallery.
Now I need to make a gallery of images with Gif, so I found this project. LINK
My project uses Fragmets I am trying to convert this project above in mine, however I am having problems in the call Activity.
The initial project activity looks like this:
package com.tenor.android.demo.search.activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.tenor.android.core.constant.StringConstant;
import com.tenor.android.core.model.impl.Tag;
import com.tenor.android.core.response.BaseError;
import com.tenor.android.core.util.AbstractUIUtils;
import com.tenor.android.core.widget.adapter.AbstractRVItem;
import com.tenor.android.demo.search.R;
import com.tenor.android.demo.search.adapter.TagsAdapter;
import com.tenor.android.demo.search.adapter.decorations.MainTagsItemDecoration;
import com.tenor.android.demo.search.adapter.rvitem.TagRVItem;
import com.tenor.android.demo.search.adapter.view.IMainView;
import com.tenor.android.demo.search.presenter.IMainPresenter;
import com.tenor.android.demo.search.presenter.impl.MainPresenter;
import com.tenor.android.demo.search.widget.TenorStaggeredGridLayoutManager;
import java.util.ArrayList;
import java.util.List;
/**
* For the MainActivity, we will display a search bar followed by a stream of Tags pulled from the Tenor API.
* Either by clicking on a tag or entering a search, SearchActivity will open.
*/
public class MainActivity extends AppCompatActivity implements IMainView{
// Number of columns for the RecyclerView
private static final int STAGGERED_GRID_LAYOUT_COLUMN_NUMBER = 2;
// Minimum length a search term can be
private static final int TEXT_QUERY_MIN_LENGTH = 2;
// A search box for entering a search term
public EditText mEditText;
// RecyclerView to display the stream of Tags
public RecyclerView mRecyclerView;
// Api calls for MainActivity performed here
private IMainPresenter mPresenter;
// Adapter containing the tag items/view holders
private TagsAdapter mTagsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditText = (EditText) findViewById(R.id.am_et_search);
mEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
final String query = textView.getText().toString().trim();
if (query.length() < TEXT_QUERY_MIN_LENGTH) {
Toast.makeText(MainActivity.this, getString(R.string.search_error), Toast.LENGTH_LONG).show();
return true;
}
// The keyboard enter will perform the search
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
startSearch(query);
return true;
}
return false;
}
});
mRecyclerView = (RecyclerView) findViewById(R.id.am_rv_tags);
mRecyclerView.addItemDecoration(new MainTagsItemDecoration(getContext(), AbstractUIUtils.dpToPx(this, 2)));
// Two column, vertical display
final TenorStaggeredGridLayoutManager layoutManager = new TenorStaggeredGridLayoutManager(STAGGERED_GRID_LAYOUT_COLUMN_NUMBER,
StaggeredGridLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(layoutManager);
mTagsAdapter = new TagsAdapter<>(this);
mRecyclerView.setAdapter(mTagsAdapter);
mPresenter = new MainPresenter(this);
mPresenter.getTags(getContext(), null);
}
private void startSearch(#Nullable final CharSequence text) {
final String query = !TextUtils.isEmpty(text) ? text.toString().trim() : StringConstant.EMPTY;
Intent intent = new Intent(this, SearchActivity.class);
intent.putExtra(SearchActivity.KEY_QUERY, query);
startActivity(intent);
}
#Override
public Context getContext() {
return getBaseContext();
}
#Override
public void onReceiveReactionsSucceeded(List<Tag> tags) {
// Map the tags into a list of TagRVItem for the mTagsAdapter
List<AbstractRVItem> list = new ArrayList<>();
for (Tag tag : tags) {
list.add(new TagRVItem(TagsAdapter.TYPE_REACTION_ITEM, tag));
}
mTagsAdapter.insert(list, false);
}
#Override
public void onReceiveReactionsFailed(BaseError error) {
// For now, we will just display nothing if the tags fail to return
}
}
Here my first change:
Note that I changed the class name to not conflict with my MainActivity
public class MainActivityGif extends Fragment implements IMainView {
And here
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//setContentView(R.layout.activity_main_gif);
View view = inflater.inflate(R.layout.activity_main_gif, container, false);
How can I call a fragment within another fragment?
private void startSearch(#Nullable final CharSequence text) {
final String query = !TextUtils.isEmpty(text) ? text.toString().trim() : StringConstant.EMPTY;
Intent intent = new Intent(getActivity(), SearchActivity.class);
intent.putExtra(SearchActivity.KEY_QUERY, query);
MainActivityGif.this.startActivity(intent);
}
If I miss the way to ask, I'm sorry, let me understand where I went wrong.
private FragmentManager mFragmentManager;
private FragmentTransaction mFragmentTransaction;
and inside your onCreate
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
and on click call :
FragmentB fragment = new FragmentB ();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.contentFragment, fragment );
mFragmentTransaction.commit();

How to add a button to Firebase Recycler view in Android?

I want to add a button for each item in the Firebase recycler view.
I've created the button, it's being showed, and i'm receiving the Toast when I press it.
But - How can I get the relevant item on it's list ?
For example - When I press the 'DELETE' I want to delete that certain mission 'aspodm'. (Sorry for the large picture, how do I make it smaller?)
This is how the database looks like (vfPvsk... is the user id, and 773f... is random uuid for mission id):
And that is the code of the relevant fragment. (The Toast when clicking the button is activated - I just don't know how to get to the relevant mission in order to delete it)
package com.airpal.yonatan.airpal;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
/**
* A simple {#link Fragment} subclass.
*/
public class PendingFragment_User extends Fragment {
private String TAG = "dDEBUG";
private RecyclerView mPendingList;
private DatabaseReference mMissionsDb;
private FirebaseAuth mAuth;
private String mCurrent_user_id;
private View mMainView;
Query queries;
public PendingFragment_User() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mMainView = inflater.inflate(R.layout.fragment_pending_user, container, false);
mPendingList = (RecyclerView)mMainView.findViewById(R.id.pending_recycler_user);
mAuth = FirebaseAuth.getInstance();
mCurrent_user_id = mAuth.getCurrentUser().getUid();
mMissionsDb = FirebaseDatabase.getInstance().getReference().child("Missions").child(mCurrent_user_id);
queries = mMissionsDb.orderByChild("status").equalTo("Available");
mMissionsDb.keepSynced(true);
mPendingList.setHasFixedSize(true);
mPendingList.setLayoutManager(new LinearLayoutManager(getContext()));
// Inflate the layout for this fragment
return mMainView;
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Mission, PendingFragment_User.MissionsViewHolder> firebaseMissionsUserRecyclerAdapter = new FirebaseRecyclerAdapter<Mission, PendingFragment_User.MissionsViewHolder>(
Mission.class,
R.layout.missions_single_layout,
PendingFragment_User.MissionsViewHolder.class,
queries
) {
#Override
protected void populateViewHolder(PendingFragment_User.MissionsViewHolder missionViewHolder, final Mission missionModel, int missionPosition) {
// Log.d(TAG, "inside populateViewHolder" + missionModel.getType() + " , " + missionModel.getDescription());
missionViewHolder.setMissionName(missionModel.getType());
missionViewHolder.setMissionDescription(missionModel.getDescription());
missionViewHolder.setMissionStatus(missionModel.getStatus());
missionViewHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Toast.makeText(view.getContext(), "esto es un boton"+ view.getNextFocusUpId(), Toast.LENGTH_SHORT).show();
Log.d(TAG,"The button was pressed");
}
});
}
};
mPendingList.setAdapter(firebaseMissionsUserRecyclerAdapter);
}
public static class MissionsViewHolder extends RecyclerView.ViewHolder {
View mView;
Button button ;
public MissionsViewHolder(View itemView) {
super(itemView);
mView = itemView;
button = (Button)mView.findViewById(R.id.pending_single_button);
}
public void setMissionName(String name){
TextView mMissionNameView = mView.findViewById(R.id.mission_single_name);
mMissionNameView.setText(name);
}
public void setMissionStatus(String status){
TextView mMissionStatusView = mView.findViewById(R.id.mission_single_status);
mMissionStatusView.setText(status);
if (status.equals("Available")){
mMissionStatusView.setTextColor(Color.parseColor("#008000"));;
} else {
mMissionStatusView.setTextColor(Color.parseColor("#FF0000"));;
}
}
public void setMissionDescription(String description){
TextView mMissionDescriptionView = mView.findViewById(R.id.mission_single_description);
mMissionDescriptionView.setText(description);
}
}
}
Try using a subclass rather than anonymous one. Then, you'll be able to access the getItem(int position) method of the adapter. Something along the lines of:
private class MissionAdapter extends FirebaseRecyclerAdapter<Mission, PendingFragment_User.MissionsViewHolder> {
public MissionAdapter(Query queries){
super(Mission.class, R.layout.missions_single_layout, PendingFragment_User.MissionsViewHolder.class, queries);
}
#Override
protected void populateViewHolder(PendingFragment_User.MissionsViewHolder missionViewHolder, final Mission missionModel, final int missionPosition) {
Log.d(TAG, "inside populateViewHolder" + missionModel.getType() + " , " + missionModel.getDescription());
missionViewHolder.setMissionName(missionModel.getType());
missionViewHolder.setMissionDescription(missionModel.getDescription());
missionViewHolder.setMissionStatus(missionModel.getStatus());
missionViewHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Mission clickedMission = MissionAdapter.this.getItem(missionPosition);
if (clickedMission != null){ // for the sake of being extra-safe
Log.d(TAG,"The button was pressed for mission: " + clickedMission.getType());
}
}
});
}
}
I made it print a log, but you should be able to do anything you want with the retrieved Mission object in there.

Error in addSlide method in appintro in android studio

There is an error in this line:
addSlide(AppIntroSampleSlider.newInstance(R.layout.app_intro1));
addSlide (android.support.v4.app.Fragment)
In AppIntroBase, it cannot be applied
My code is here:
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
import com.github.paolorotolo.appintro.AppIntro;
/**
* Created by Arvind on 2/6/2017.
*/
public class MyIntro extends AppIntro {
#Override
public void init(Bundle savedInstanceState) {
//adding the three slides for introduction app you can ad as many you needed
addSlide(AppIntroSampleSlider.newInstance(R.layout.app_intro1));
addSlide(AppIntroSampleSlider.newInstance(R.layout.app_intro2));
addSlide(AppIntroSampleSlider.newInstance(R.layout.app_intro3));
// Show and Hide Skip and Done buttons
showStatusBar(false);
showSkipButton(false);
// Turn vibration on and set intensity
// You will need to add VIBRATE permission in Manifest file
setVibrate(true);
setVibrateIntensity(30);
//Add animation to the intro slider
setDepthAnimation();
}
#Override
public void onSkipPressed() {
// Do something here when users click or tap on Skip button.
Toast.makeText(getApplicationContext(),
getString(R.string.app_intro_skip), Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
#Override
public void onNextPressed() {
// Do something here when users click or tap on Next button.
}
#Override
public void onDonePressed() {
// Do something here when users click or tap tap on Done button.
finish();
}
#Override
public void onSlideChanged() {
// Do something here when slide is changed
}
}
I created a class i.e. AppIntroSampleSlider.
My AppIntroSampleSlider class is:
package com.example.arvind.appintro1;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Arvind on 13-Feb-17.
*/
public class AppIntroSampleSlider extends Fragment {
private static final String ARG_LAYOUT_RES_ID = "layoutResId";
public static AppIntroSampleSlider newInstance(int layoutResId) {
AppIntroSampleSlider sampleSlide = new AppIntroSampleSlider();
Bundle bundleArgs = new Bundle();
bundleArgs.putInt(ARG_LAYOUT_RES_ID, layoutResId);
sampleSlide.setArguments(bundleArgs);
return sampleSlide;
}
private int layoutResId;
public AppIntroSampleSlider() {}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getArguments() != null && getArguments().containsKey(ARG_LAYOUT_RES_ID))
layoutResId = getArguments().getInt(ARG_LAYOUT_RES_ID);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(layoutResId, container, false);
}
}
I want to why it is showing error in the code.So Please help me to solve this error.
I found a better example without error
http://www.androidhive.info/2016/05/android-build-intro-slider-app/
AppIntro library works best with the following import in your AppIntroSampleSlider.java file:
import android.support.v4.app.Fragment;
Instead of:
import android.app.Fragment;

Passing Boolean value from fragments to activity

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;
}
}

How can I make a fragment replace actionbar menu behavior?

Before I start, yes I have read countless related questions. I still can't seem to track down the issue.
I have a SherlockFragmentActivity:
package com.kicklighterdesignstudio.floridaday;
import android.os.Bundle;
import android.support.v4.app.Fragment;
public class FragmentActivity extends BaseActivity {
public static final String TAG = "FragmentActivity";
public static final int SCHEDULE_FRAGMENT = 0;
public static final int MAP_FRAGMENT = 1;
public static final int FOOD_FRAGMENT = 2;
public static final int TWITTER_FRAGMENT = 3;
public static final int HASHTAG_FRAGMENT = 4;
private Fragment mContent;
public FragmentActivity() {
super(R.string.main_activity_title);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_frame);
switchContent(SCHEDULE_FRAGMENT);
setBehindContentView(R.layout.menu_frame);
}
public void switchContent(int id) {
getFragment(id);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, mContent)
.commit();
getSlidingMenu().showContent();
}
private void getFragment(int id) {
switch (id) {
case 0:
mContent = new ScheduleFragment();
break;
case 1:
mContent = new FoodFragment();
break;
case 2:
mContent = new MapFragment();
break;
case 3:
mContent = new TwitterFragment();
break;
case 4:
mContent = new HashtagFragment();
break;
}
}
}
It extends BaseActivity:
package com.kicklighterdesignstudio.floridaday;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import com.actionbarsherlock.view.MenuItem;
import com.slidingmenu.lib.SlidingMenu;
import com.slidingmenu.lib.app.SlidingFragmentActivity;
public class BaseActivity extends SlidingFragmentActivity {
// private int mTitleRes;
protected ListFragment mFrag;
public BaseActivity(int titleRes) {
// mTitleRes = titleRes;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setTitle(mTitleRes);
setTitle("");
// set the Behind View
setBehindContentView(R.layout.menu_frame);
if (savedInstanceState == null) {
FragmentTransaction t = this.getSupportFragmentManager().beginTransaction();
mFrag = new MenuFragment();
t.replace(R.id.menu_frame, mFrag);
t.commit();
} else {
mFrag = (ListFragment) this.getSupportFragmentManager().findFragmentById(
R.id.menu_frame);
}
// customize the SlidingMenu
SlidingMenu sm = getSlidingMenu();
sm.setShadowWidthRes(R.dimen.shadow_width);
sm.setShadowDrawable(R.drawable.shadow);
sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
sm.setFadeDegree(0.35f);
sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
sm.setBehindScrollScale(0.0f);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
toggle();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Right now, I'm only concerned with ScheduleFragment:
package com.kicklighterdesignstudio.floridaday;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.actionbarsherlock.app.SherlockFragment;
public class ScheduleFragment extends SherlockFragment implements OnItemClickListener {
public static final String TAG = "ScheduleFragment";
private ArrayList<ScheduleItem> schedule;
private FloridaDayApplication app;
public ScheduleFragment() {
// setRetainInstance(true);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
app = (FloridaDayApplication) activity.getApplication();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.schedule_fragment, container, false);
}
#Override
public void onStart() {
super.onStart();
getSherlockActivity().getSupportActionBar().setTitle(R.string.schedule_fragment);
schedule = app.getSchedule();
ListView scheduleListView = (ListView) getActivity().findViewById(R.id.schedule_list);
ScheduleItemAdapter adapter = new ScheduleItemAdapter(getActivity(), schedule);
scheduleListView.setAdapter(adapter);
scheduleListView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> a, View v, int id, long position) {
Fragment newFragment = new ScheduleItemFragment(id);
FragmentTransaction transaction = getSherlockActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content_frame, newFragment).addToBackStack(null).commit();
}
}
ScheduleFragment displays a list of schedule items. When clicked, a new fragment is displayed (ScheduleItemFragment) to show details of the item and a map to its location:
package com.kicklighterdesignstudio.floridaday;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.model.MarkerOptions;
#SuppressLint("ValidFragment")
public class ScheduleItemFragment extends SherlockFragment {
public static final String TAG = "ScheduleItemFragment";
private int scheduleItemId;
private FloridaDayApplication app;
private ScheduleItem scheduleItem;
private MapView mapView;
private GoogleMap map;
public ScheduleItemFragment(int id) {
scheduleItemId = id;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
app = (FloridaDayApplication) activity.getApplication();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.schedule_item_fragment, container, false);
setHasOptionsMenu(true);
// Initialize MapView
mapView = (MapView) v.findViewById(R.id.map_view);
mapView.onCreate(savedInstanceState);
return v;
}
#Override
public void onStart() {
super.onStart();
scheduleItem = app.getSchedule().get(scheduleItemId);
getSherlockActivity().getSupportActionBar().setTitle(scheduleItem.getTitle());
// Map Stuff
map = mapView.getMap();
if (map != null) {
map.getUiSettings();
map.setMyLocationEnabled(true);
try {
MapsInitializer.initialize(getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
// Add marker to the map
MarkerOptions options = new MarkerOptions().position(scheduleItem.getLocation().getPosition()).title(
scheduleItem.getLocation().getTitle());
map.addMarker(options);
// Adjust Camera Programmatically
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
scheduleItem.getLocation().getPosition(), 14);
map.animateCamera(cameraUpdate);
} else {
Log.i(TAG, "Map is null");
}
// Other Views
TextView title = (TextView) getSherlockActivity().findViewById(R.id.title);
TextView time = (TextView) getSherlockActivity().findViewById(R.id.time);
TextView description = (TextView) getSherlockActivity().findViewById(R.id.description);
title.setText(scheduleItem.getTitle());
time.setText(scheduleItem.getDateTimeString());
description.setText(scheduleItem.getDescription());
}
// TODO: Make this work
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
getFragmentManager().popBackStack();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public void onDestroy() {
mapView.onDestroy();
super.onDestroy();
}
#Override
public void onLowMemory() {
mapView.onLowMemory();
super.onLowMemory();
}
#Override
public void onPause() {
mapView.onPause();
super.onPause();
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onSaveInstanceState(Bundle outState) {
mapView.onSaveInstanceState(outState);
super.onSaveInstanceState(outState);
}
}
Thanks to BaseActivity, the icon in my ActionBar is clickable. It toggles the Sliding Menu. When viewing a ScheduleItemFragment, I would like the icon to return to the previous item in the backstack (which you can see I'm trying to do.) No matter what I try, the icon always toggles the Sliding Menu. Any thoughts on how to guarantee my Fragment gains control of the ActionBar menu clicks?
you need to call setHasOptionsMenu(true); in onCreate, not onCreateView
also I'm interested what happens when you debug, does onOptionsItemSelected still get called?
edit: add the following to your fragment
#Override
public void onCreate(Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
edit1:
there may be a better way to do this but I'm not exactly sure how your fragments are setup out, create a public field in baseActivity public bool isItemFragmentOnTop
now onOptionsItemSelected in the case of the home button getting press do this
if (isItemFragmentOnTop){
getFragmentManager().popBackStack();
isItemFragmentOnTop = false;
} else {
toggle();
}
return true;
then in your fragment you can call ((BaseActivity)getActivity).isItemFragmentOnTop = true; to make the home button pop the back stack, you would want to do this when you display your fragment onItemClick in your list view.

Categories

Resources