ListFragment called from Button - java

This batch of code will place a ListFragment into a LinearLayout that I have selected, and it works fine. The problem I have is that this initiates from onCreate and I would like it to trigger from a Button.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TamInputListFragment lstfragment=(TamInputListFragment)getSupportFragmentManager().findFragmentByTag("lstfragment");
if(lstfragment==null){
lstfragment=new TamInputListFragment();
FragmentTransaction transact=getSupportFragmentManager().beginTransaction();
transact.add(R.id.fragment_container,lstfragment,"lstfragment");
transact.commit();
}
This batch of code worked for a previous tutorial that just interchanged two simple Fragment with two separate Button.
public void selectFrag(View view){
Fragment fr;
if (view == findViewById(R.id.button2)) {
fr = new FragmentTwo();
}
else {
fr = new FragmentOne();
}
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr);
fragmentTransaction.commit();
}
But when I use this same batch of code and swap out FragmentOne() and FragmentTwo() for the two new ListFragment classes that I have made, TamInputListFragment and VerbInputListFragment, I get an "Incompatible Type" error saying that is wants a android.app.Fragment and not a com.example.petakirikiri.fragmenttest.Fragments.TamInputListFragment();
public void selectFrag(View view){
Fragment fr;
if (view == findViewById(R.id.verb_button) {
fr = new TamInputListFragment();
}
else {
fr = new VerbInputListFragment();
}
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fr);
fragmentTransaction.commit();
}

Related

Bottom navigation not working. How to resolve this issue?

I have made the code to do that it loads fragment on clicking the items in the bottom navigation but when I click on it they don't work. I tried many times to check whats the problem even though Android Studio couldn't find it bu the app isn't working. I don't know whats the issue.
My main activity -
public class MainActivity extends AppCompatActivity {
BottomNavigationView btm_view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = manager.beginTransaction();
fragmentTransaction.add(R.id.container, new Chats());
fragmentTransaction.commit();
btm_view = findViewById(R.id.bottom_view);
btm_view.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.camera) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = manager.beginTransaction();
fragmentTransaction.add(R.id.container, new Camera());
fragmentTransaction.commit();
} else if (item.getItemId() == R.id.chats) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = manager.beginTransaction();
fragmentTransaction.add(R.id.container, new Chats());
fragmentTransaction.commit();
} else if (item.getItemId() == R.id.status) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = manager.beginTransaction();
fragmentTransaction.add(R.id.container, new Status());
fragmentTransaction.commit();
} else if (item.getItemId() == R.id.calls) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = manager.beginTransaction();
fragmentTransaction.add(R.id.container, new Calls());
fragmentTransaction.commit();
} else if (item.getItemId() == R.id.settings) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = manager.beginTransaction();
fragmentTransaction.add(R.id.container, new Settings());
fragmentTransaction.commit();
}
return false;
}
});
}
}
one of my fragments -
public class Chats extends Fragment {
public Chats() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_chats, container, false);
}
}
Try this way
BottomNavigationView.OnNavigationItemSelectedListener navigationItemSelectedListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.chats:
openFragment(Chat.newInstance());
return true;
case R.id.camera:
openFragment(Camera.newInstance());
return true;
case R.id.status:
openFragment(Status.newInstance("", ""));
return true;
}
return false;
}
};
At first use replace(R.id.container, fragment) instead of add.
Optimise Code
Utilise setOnNavigationItemSelectedListener. Try this way
Set a listener that will be notified when a bottom navigation item is
selected.
btm_view.setOnNavigationItemSelectedListener(navigationItemSelectedListener);
openFragment(Camera.newInstance());
}
public void openFragment(Fragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
BottomNavigationView.OnNavigationItemSelectedListener navigationItemSelectedListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.camera:
openFragment(Camera.newInstance());
return true;
case R.id.chats:
openFragment(Chats.newInstance());
return true;
case R.id.status:
openFragment(Status.newInstance());
return true;
case R.id.calls:
openFragment(Calls.newInstance());
return true;
case R.id.settings:
openFragment(Settings.newInstance());
return true;
}
return false;
}
};
}
Your Chats Fragment will be
public class Chats extends Fragment {
public Chats() {
// Required empty public constructor
}
public static Chats newInstance() {
Chats fragment = new Chats();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_chats, container, false);
}
}

How to Save the last Fragment?

I have three Fragments and I have two buttons on main Activity b1 called next button and b2 called previous button when app is starting its show me blank Fragment , when click on b1 its show me XFragment called page 1 ,when click on b1 its show me YFragment called page 2 , I want when re-open app its show me the last Fragment has been opend ,I know should use shareprefrences but I dont know how to add it to this code
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void b1(View view) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
XFragment fragment = new XFragment();
ft.replace(R.id.mainfragment,fragment);
ft.commit();
}
public void b2(View view) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
YFragment fragment = new YFragment();
ft.replace(R.id.mainfragment,fragment);
ft.commit();
}
}
Below is your required code using SharedPreference.
public class MainActivity extends AppCompatActivity {
SharedPreference pref;
Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = getApplicationContext().getSharedPreferences("MyPref", 0);
editor = pref.edit();
int fragment_number=pref.getInt("fragment_number", -1); // getting Integer
if(int==1){
//start first fragment
}
if(int==2){
//start second fragment
}
}
public void b1(View view) {
editor.putInt("fragment_number", 1);
editor.apply();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
XFragment fragment = new XFragment();
ft.replace(R.id.mainfragment,fragment);
ft.commit();
}
public void b2(View view) {
editor.putInt("fragment_number", 2);
editor.apply();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
YFragment fragment = new YFragment();
ft.replace(R.id.mainfragment,fragment);
ft.commit();
}
}

How to replace fragment onclick of button inside if condition true?

fragment replacement not working if i put if condition in below code..
_doneButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View _view) {
Name(no.getText().toString(), pass.getText().toString());
if(loginsucess){
android.support.v4.app.FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
MainFragment mainFragment = new MainFragment();
ft.replace(R.id.content, mainFragment);
ft.addToBackStack(null);
ft.commit();
}
_doneButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View _view) {
if(true){
Name(no.getText().toString(), pass.getText().toString());
android.support.v4.app.FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
MainFragment mainFragment = new MainFragment();
ft.replace(R.id.content, mainFragment);
ft.addToBackStack(null);
ft.commit();
}
Try this
if(loginsucees){
android.support.v4.app.FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
MainFragment mainFragment = new MainFragment();
ft.replace(R.id.content, mainFragment);
ft.addToBackStack(null);
ft.commit();
}
else {
//Do Nothing
}
_doneButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View _view) {
if(loginsucees){
Name(no.getText().toString(), pass.getText().toString());
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
MainFragment mainFragment = new MainFragment();
ft.replace(R.id.content, mainFragment,"main_fragment");
ft.commitAllowingStateLoss();
}
}
});

How to add/remove Fragment on Button click?

At present I have got a "RELATIVE_LAYOUT" container which I am using for adding my fragment.
I am using OnClickListener on a button to load the fragment XML layout into the RelativeLayout container.
What I want to achieve is that when I press the button once, the fragment should load...and when I press it again the fragment should be removed. I've already tried using integer to identify if fragment is loaded, but failed.
Any help Appreciated...
CODE:
public class MainActivity extends Activity {
Button B1,B2;
int boolb1=0, boolb2=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
B1 = (Button)findViewById(R.id.btn1);
B2 = (Button)findViewById(R.id.btn2);
B1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
FragmentOne f1 = new FragmentOne();
if(boolb1==0)
{ft.add(R.id.frg1, f1);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
boolb1=1;}
else
{ft.remove(f1);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
boolb1=0;}
//ft.addToBackStack("f1");
ft.commit();
}
});
B2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
FragmentTwo f2 = new FragmentTwo();
if(boolb2==0) {
ft.add(R.id.frg2, f2);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
boolb2=1;
} else {
ft.remove(f2);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
boolb2=0;
}
//ft.addToBackStack("f2");
ft.commit();
}
});
}
Your issue is that you create a new Fragment everytime you click the Button. You need to get a reference to the currently added Fragment and then remove that one.
Furthermore, you no longer need to use the flag.
When adding the Fragment, you can tag it. Upon removing the Fragment, you can use the tag used for adding the Fragment to get a reference to the currently added Fragment.
Here is an example of how you should do it:
private Button B1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
B1 = (Button)findViewById(R.id.btn1);
B1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
FragmentOne f = (FragmentOne) fm.findFragmentByTag("tag");
if(f == null) { // not added
f = new FragmentOne();
ft.add(R.id.frg1, f, "tag");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
} else { // already added
ft.remove(f);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
}
ft.commit();
}
});
// and so on ...
}

How do I add structure to UI built on Fragments?

I build an app, which consists of Activity and Fragments, which reside in the Activity.
I replace Fragments according with the app flow, but it seems that as more actions are added to the app, it becomes more hard to keep track of the app flow in code.
Suppose this:
public class MainActivity extends Activity{
private enum AppState {
WAIT_SIGN_IN, SCAN_PERSONAL_ID, CONFIRM_ORDER, PICK_ITEM, NAVIGATE_TO_ITEM
}
private AppState currentState = AppState.WAIT_SIGN_IN;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setWaitSignInContent();
}
//Hardware key is pressed
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (currentState) {
case WAIT_SIGN_IN:
setSignInContent();
currentState = AppState.SCAN_PERSONAL_ID;
break;
case PICK_ITEM:
handlePickItem();
default:
break;
}
return true;
}
//Callback from barcode scanner
#Override
public void onCodeScanned(String code) {
switch (currentState) {
case SCAN_PERSONAL_ID:
if (checkPersonalId(code)) {
setSignInSuccessContent();
}
break;
default:
break;
}
}
private void setSignInSuccessContent() {
Fragment fragment = new ImageFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_primary, fragment).commit();
}
private void setSignInContent() {
Fragment fragment = new ScannerFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_primary, fragment).commit();
}
private void setWaitSignInContent() {
Fragment fragment = new ImageFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_primary, fragment).commit();
}
}
}
As you can see, this state-based flow is hard to follow. Any suggestions on how to improve that?
i'm follow this way to replace fragment
create method in your activity for adding and replacing.
public void addFragments(Fragment fragment, boolean animate,
boolean addToBackStack, String tag) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
if (animate) {
// ft.setCustomAnimations(R.anim.fragment_from_right,
// R.anim.fragment_from_left, R.anim.fragment_from_right,
// R.anim.fragment_from_left);
}
if (addToBackStack) {
ft.addToBackStack(tag);
}
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
// remove all fragments from the stack
public void removeAllFragment(Fragment replaceFragment, boolean animate,
boolean addToBackStack, String tag) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
manager.popBackStackImmediate(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
if (animate) {
// ft.setCustomAnimations(R.anim.slide_in_right,
// R.anim.slide_out_left);
// ft.setCustomAnimations(R.anim.fragment_from_right,
// R.anim.fragment_from_left, R.anim.fragment_from_right,
// R.anim.fragment_from_left);
}
if (addToBackStack) {
ft.addToBackStack(tag);
}
ft.replace(R.id.content_frame, replaceFragment);
ft.commit();
}
now override in Fragment
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof MainActivity) {
mainActivity = (MainActivity) activity;
}
}
now just call in fragment for replace like
mainActivity.addFragments(new BusinessDetail(), true, tr, null);
enjoy i hope it helps.
Since there seems to be only one activity in your app, you migh consider using the singleton pattern (the activity itself being that singleton, obviously). For example, your interface may look like this:
public void addFragment(Fragment fragment, boolean replaceTopFragmentInStack);
public void removeFragment(Fragment fragment);
public void removeFragment(int index);
public void removeTopFragment();
public void clearFragmentStack();
Not only you will be able to easily control the flow, but you will also have access to these methods from anywhere in the app via something like MainActivity.getInstance().removeTopFragment()

Categories