Switch from Activity to the recent fragment visited in BottomNavigationView - floating-action-button

I am trying to make a social media app , Im using fragments within BottomNavigation (home - smart room - notifications - profile), And Im using a floating button to switch to "Add post" activity , Now Im having a problem with the back button , i want it to take me to the recent visited fragment but it always take me to the home fragment
here is my BottomNavigation activity code :
public class BottomNavigationActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bottom_navigation);
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation_layout);
//setEnabled(false) for the 2nd index because we're using a floating button instead
bottomNav.setBackground(null);
bottomNav.getMenu().getItem(2).setEnabled(false);
bottomNav.setOnItemSelectedListener(navListener);
//start AddPostActivity class
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), AddPostActivity.class));
finish();
}
});
}
//Switch between fragments
public BottomNavigationView.OnItemSelectedListener navListener =
new BottomNavigationView.OnItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.nav_home:
selectedFragment = new HomeFragment();
break;
case R.id.nav_sr:
selectedFragment = new SmartRoomFragment();
break;
case R.id.nav_notif:
selectedFragment = new NotificationsFragment();
break;
case R.id.nav_profile:
selectedFragment = new ProfileFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
return true;
}
};
}
I want the best solution to handle this problem , thanks in advance!

Related

how to send data from popup window to a tabbed activity having fragments?

mainActivity has button. After button is clicked a popup message show having a button and a TextInputLayout.
data is sent to a tabbed acticity having 2 fragments and
the data is shown in textview of first fragment. Error is the data wont show in the textview while running
adapter for 2 fragments--
public class adapter extends FragmentPagerAdapter {
public adapter(#NonNull FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Fragment getItem(int position) {
Fragment fragment;
if (position == 1) {
fragment = new SecondFragment();
} else {
fragment = new FirstFragment();
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
String title = null;
if (position == 0) {
title = "TextView";
} else if (position == 1) {
title = "Listview";
}
return title;
}
}
mainActivity(having popup window on clicking button)
myDialog = new Dialog(this);
}
//for for joining match
public void ShowPopup(View view) {
myDialog.setContentView(R.layout.popup);
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
myDialog.show();
name = myDialog.findViewById(R.id.ig_name);
String igname = Objects.requireNonNull(name.getEditText()).getText().toString();
entry = myDialog.findViewById(R.id.entry);
entry.setOnClickListener(v -> {
Intent intent = new Intent(getApplicationContext(), secondActivity.class);
intent.putExtra("igname", igname);
startActivity(intent);
finish();
});
}
}
my firstFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_first, container, false);
secondActivity activity = (secondActivity) getActivity();
TextView output = view.findViewById(R.id.textshow);
Bundle results = activity.getMyData();
String value1 = results.getString("value");
output.setText(value1);
return view;
}
secondActivity (intent is transfered from popup window)
public class secondActivity extends AppCompatActivity {
private String name;
TabLayout tabLayout;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(new adapter(getSupportFragmentManager()));
tabLayout = findViewById(R.id.tabs_layout);
tabLayout.setupWithViewPager(viewPager);
Intent intent = getIntent();
name = intent.getExtras().getString("igname");
}
public Bundle getMyData() {
Bundle bundle = new Bundle();
bundle.putString("value", name);
return bundle;
}
}
Get the "igname" String value in onClickListner & also dismiss the dialog before finishing the activity.
entry.setOnClickListener(v -> {
String igname = Objects.requireNonNull(name.getEditText()).getText().toString();
Intent intent = new Intent(getApplicationContext(), secondActivity.class);
intent.putExtra("igname", igname);
startActivity(intent);
finish();
});

Cannot close a custom AlertDialog

so I have an app with three different buttons(parent buttons) on pressing any of them, the custom alert dialog with 9 different buttons is displayed but the functions of these 9 buttons within the alert dialog are different depending on which of the three parent buttons called it. On pressing any of the 9 buttons, I want the app to perform a particular function and then close the alertdialog. Now the problem is that I can easily call the alert dialog by calling the method showcustomdialog(); that I created but I can't dismiss it using alertdialog.dismiss(); inside the OnClickListener of the parent button since the method has a void result type. I've tried using if-else statements but it doesn't work. How can I achieve what is required?
The method:
private void showCustomDialog() {
ViewGroup viewGroup = findViewById(android.R.id.content);
View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_main2, viewGroup, false);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(dialogView);
final AlertDialog alertDialog = builder.create();
alertDialog.show();
}
I am calling the meathod and using it as follows:
parentbutton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showCustomDialog();
alertbutton1.getId();
alertbutton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
textView1.setText("500");
function();
//I want to dismiss the alertdialog here.
}
});
alertbutton2.getId();
alertbutton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
textView1.setText("1000");
function();
//I want to dismiss the alertdialog here.
}
});
and so on.
I figured out a solution for you using AlertDialog.
parentbutton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createDialog();
}
});
Then the method MUST be a private or public AlertDialog:
private AlertDialog createDialog() {
LayoutInflater inflater = (getActivity()).getLayoutInflater(); // for fragment or getLayoutInflater(); for activity
View v = inflater.inflate(R.layout.dialog_add_new_list, null);
Button okButton = v.findViewById(R.id.confirm_button);
Button cancelButton = v.findViewById(R.id.cancel_button);
final AlertDialog dialog = new AlertDialog.Builder(getActivity()) // for fragment or AlertDialog.Builder ( this ) for activity
.setView(v)
.show();
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View p1) {
dialog.dismiss();
}
});
return dialog;
}
P.S. Replace the ids I used to create this sample with yours.

setLayout not inflating correct xml layout?

been alright so far. I try to use docs or find my issues.
However my mainActivity has 4 buttons. These buttons depending on which view is clicked passes the R.id.button. I pass this value into an intent which Activity2 uses bundle to get id integer. I then setContentView using this.
However im having issues getting correct view to inflate now, it seems like its loading an old layout. My aim is to inflate 3 separate layout on Activity2 depending which button was clicked.
I know my other other button does inflate another activity and get proper xml layout.
Why are my other 3 buttons not inflating on Activity2 properly?
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button pizza;
Button hamburger;
Button icecream;
Button history;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pizza = findViewById(R.id.buttonPizza);
hamburger = findViewById(R.id.buttonBurger);
icecream = findViewById(R.id.buttonIceCream);
history = findViewById(R.id.buttonHistroy);
pizza.setOnClickListener(this);
hamburger.setOnClickListener(this);
icecream.setOnClickListener(this);
history.setOnClickListener(this);
}
#Override
public void onClick(View v){
int idView = v.getId();
switch(v.getId()) {
case R.id.buttonBurger : startOrderActivity(R.layout.burger_layout);
makeToast(idView);
break;
case R.id.buttonPizza : startOrderActivity(R.layout.pizza_layout);
makeToast(idView);
break;
case R.id.buttonIceCream : startOrderActivity(R.layout.icecream_layout);
makeToast(idView);
break;
case R.id.buttonHistroy : startOrderActivity(R.layout.history_layout);
makeToast(idView);
break;
}
}
private void startOrderActivity(int id){
if(id != R.layout.history_layout) {
Intent intentOrder = new Intent(this, MakeOrderActivity.class);
intentOrder.putExtra("layout", id);
startActivity(intentOrder);
}
else {
Intent intentOrder = new Intent(this, OrderHistoryActivity.class);
intentOrder.putExtra("layout", id);
startActivity(intentOrder);
}
}
public void makeToast(int id){
String txt = String.valueOf(id);
Toast newToast = Toast.makeText(getApplicationContext(),txt,Toast.LENGTH_LONG);
newToast.show();
}
}
public class MakeOrderActivity extends AppCompatActivity {
Button placeOrderButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle data = getIntent().getExtras();
int layoutNum = data.getInt("layout");
setContentView(layoutNum);
placeOrderButton = findViewById(R.id.placeOrder);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.order, menu);
return true;
}
public void onCheckboxClicked(View view){
}
}
Answer is to create a View which is created by getInflator.
https://stackoverflow.com/a/17070408/8443090

Going to Main Activity from fragment

I implemented a navigation drawer and had used fragments. Now i can switch to fragments from the drawer menu. But when i press back, my app closes from that fragment and don't know how to go back to the main activity.
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
displaySelectedScreen(id);
return true;
}
private void displaySelectedScreen(int id) {
Fragment frag = null;
switch (id) {
case R.id.trigger:
break;
case R.id.setup:
if (android.os.Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(Color.parseColor("#7B1FA2"));
}
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#8E24AA")));
frag = new SettingsF();
break;
case R.id.recordings:
if (android.os.Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(Color.parseColor("#4E342E"));
}
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#8D6E63")));
break;
case R.id.howto:
if (android.os.Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(Color.parseColor("#7B1FA2"));
}
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#8E24AA")));
break;
case R.id.about:
if (android.os.Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(Color.parseColor("#7B1FA2"));
}
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#8E24AA")));
break;
case R.id.email_us:
if (android.os.Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(Color.parseColor("#7B1FA2"));
}
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#8E24AA")));
break;
}
if (frag != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_main, frag);
ft.addToBackStack(ft.getClass().getSimpleName()).commit();
}
DrawerLayout drawer = findViewById(R.id.drawer);
drawer.closeDrawer(GravityCompat.START);
}
And here is the setting fragment only:
public class SettingsF extends ListFragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_settings, container, false);
String[] datasource = {"Trusted Contacts", "Custom Text Set-Up"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.rowlayout, R.id.txtitems, datasource);
setListAdapter(adapter);
setRetainInstance(true);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Context Set-Up");
}
public void onListItemClick(ListView l, View view, int position, long id) {
ViewGroup viewGroup = (ViewGroup) view;
TextView tv = (TextView) viewGroup.findViewById(R.id.txtitems);
Toast.makeText(getActivity(), tv.getText().toString(), Toast.LENGTH_LONG).show();
}
#Override
public void onResume() {
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener( new View.OnKeyListener()
{
#Override
public boolean onKey( View v, int keyCode, KeyEvent event )
{
if( keyCode == KeyEvent.KEYCODE_BACK )
{
//Already Used Intent, doesn't work
return true;
}
return false;
}
} );
super.onResume();
}
}
I updated the question. I already used addToBackStack(), then overrided the method onResume() but still the app terminates when pressing the back button.
I'm really that new to this, so don't misunderstand me what did i implemented throughout the codes.
Thanks In Advance
for Hardware backbutton
add this code in onResume method in fragment
//You need to add the following line
fragment.getView().setFocusableInTouchMode(true);
fragment.getView().requestFocus();
fragment.getView().setOnKeyListener( new OnKeyListener()
{
#Override
public boolean onKey( View v, int keyCode, KeyEvent event )
{
if( keyCode == KeyEvent.KEYCODE_BACK )
{
//here use intent to call mainActivity
return true;
}
return false;
}
} );
hope this will help you
Add this line after ft.replace():
ft.addToBackStack(null);
This line will make it so that each time you select an item from the navigation drawer, a history of fragments is built up. Then when you press the back button, you'll go back through the history. If you have no history items, the app will close.
A more sophisticated implementation might use a name argument (like "FragA" or "FragB") instead of null as the argument for addToBackStack(), and then check to see if your fragment already exists in the back stack instead of always opening a new one. That way if you went A->B->A->B->A->B you wouldn't have three copies of A and two copies of B in the history.

How to send data in ListView dynamicaly in android.?

My question is how do i send data written in EditText of dialogue box by clicking button and display it on LIstView of Main Activity. ?
public class TaskDetailsActivity extends Activity implements OnClickListener{
String[] timepass= new String[100];
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.taskdetails);
//timepass[0] = "sidd";
/*ListView tasklist= (ListView)findViewById(R.id.listview);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.insideaddtask, R.id.tp, timepass);
tasklist.setAdapter(adapter);*/
}
public void addnewtask(View view)
{
showDialog(1);
}
#Override
protected Dialog onCreateDialog(int id)
{
Dialog dialog=null;
switch (id)
{
case 1: dialog = new Dialog(TaskDetailsActivity.this);
dialog.setContentView(R.layout.addtask);
Button task_add_ok = (Button)findViewById(R.id.btn_ok);
task_add_ok.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
EditText writetask = (EditText)findViewById(R.id.txt_writetask);
String data = writetask.getText().toString();
timepass[0] = data;
}
});
break;
default:
break;
}
return dialog;
}
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
}
}
you can use any adapter for this arrayadapter of type string...
and use the button's onclick method to populate the listview...
below link provides a good example...
http://android.amberfog.com/?p=296
www.androidhive.info/2011/10/android-listview-tutorial/

Resources