Implementing Up navigation on fragment - java

I have a MainActivity which contains FragmentA. When I click on FragmentA, this happens:
getFragmentManager().beginTransaction().replace(R.id.container,new PrefFragment()).addToBackStack("back").commit();
I have this in my manifest:
<activity>
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstapp.MainActivity" />
</activity>
and this in MainActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_head_sound);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new FragmentA)
.commit();
}
getActionBar().setDisplayHomeAsUpEnabled(true);
}
But the Up Button navigation is always visible.
FragmentB contains this code:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id=item.getItemId();
switch (id)
{
case android.R.id.home:
getFragmentManager().popBackStack();
Toast.makeText(getActivity(),"CLick",Toast.LENGTH_SHORT).show();
break;
}
return super.onOptionsItemSelected(item);
}
This code doesn't run.
I need to implement Up navigation only in FragmentB. How can I do that?

As far as I understand the up navigation must work only in FragmentB, whereas if FragmentA is shown the up navigation will be hidden. If so, then in Activity, remove getActionBar().setDisplayHomeAsUpEnabled(true); from onCreate.
Also you must return true when you handled menu click, and move the onOptionsItemSelected(MenuItem) to Activity since android.R.id.home menu click is only delivered to the Activity.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
getFragmentManager().popBackStack();
Toast.makeText(getActivity(),"CLick",Toast.LENGTH_SHORT).show();
return true; //Notice you must returning true here
default:
return super.onOptionsItemSelected(item);
}
}
In FragmentA
#Override
public void onAttach(Activity a) {
super.onAttach(a);
a.getActionBar().setDisplayHomeAsUpEnabled(false);
}
In FragmentB
#Override
public void onAttach(Activity a) {
super.onAttach(a);
a.getActionBar().setDisplayHomeAsUpEnabled(true);
}

Related

From second activity when press home back button do not came back same fragment in a activity

In my project 2 activity given - MainActivity & Second Activity.
in my main activity, I have four fragments, In the 3rd fragment, A button uses to go to the second activity.
I will implement the below code to go back
This code came back to me on MainActivity at home Fragment. but I went through the third fragment.so I want to come back to my third fragment. Please coders help me to solve this.
Also, help me when I go from fragment to fragment and want to come back to the same fragment.
In Manifest
<activity
android:name=".SecondActivity"
android:parentActivityName=".MainActivity"
android:exported="false" />
ThirdFragment
binding.goToSecondActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent a = new Intent(getActivity(), SecondActivity.class);
a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(a);
}
});
In Second activity
public class SecondActivity extends AppCompatActivity {
ActivitySecondBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivitySecondBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
getSupportActionBar().setTitle("Second Page");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// code here
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
}
You should define a class, with a method getInstance accessible globally, that contains the last fragment visited, when you press back you should use the fragment manager to recreate the last fragment (found in the new class) and then, looking at the model of the selected fragment, repopulate it with the old data (if there are inputs/non static datas in the fragment)

How to get last Fragment used when pressing back button

I have a simple fragment with this code:
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selectedFragment= null;
switch (menuItem.getItemId()){
case R.id.nav_home:
selectedFragment= new HomeFragment();
setTitle("Beranda");
break;
case R.id.nav_message:
selectedFragment= new MessageFragment();
setTitle("Pesan");
break;
case R.id.nav_transaction:
selectedFragment= new TransactionFragment();
setTitle("Transaksi");
break;
case R.id.nav_profile:
selectedFragment= new ProfileFragment();
setTitle("Profil");
if(sessionLevel.equals("admin")){
setTitle("Admin");
}
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();
return true;
}
};
Most of the fragment are just some kind of holder for Intent Activity. And the Activity itself doesnt have some fancy code.
The problem is that when i do Intent on Profile menu and then press back, the fragment shown is HomeActivity but the selected button is Profile.
I dont know about the other 2 fragment since im not there yet, but probably they do the same thing.
You can do this like the following:
#Override
public void onBackPressed() {
super.onBackPressed();
Fragment frag = YourActivity.this.getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if(frag!=null && frag instanceof yourFragment)
{}
}
The following will give you count
int count = getSupportFragmentManager().getBackStackEntryCount();
You can make condition, If count is great than 1 then have more than 1 fragments else you have atleast 1 fragment and that will be last fragment. If count 0 then no more fragment available on stack as all have been poped out of stack.
Create an interface:
public interface IOnBackPressed {
boolean onBackPressed();
}
In Fragment implement IOnBackPressed like:
public class FAQFragment extends Fragment implements IOnBackPressed {
public boolean onBackPressed() {
return false
}
}
On Main Activity Backpress use
#Override
public void onBackPressed(){
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
}
}

How can I override the button display home

By default the button(setDisplayHomeAsUpEnabled), returns the parent activity, how would I change it? For example: I need to back to a Intent
toolbar = (Toolbar) findViewById(R.id.tb_dados);
toolbar.setTitle("Adicione uma descrição");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
You can try this....
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
// your intent code here.
break;
}
return super.onOptionsItemSelected(item);
}
you can use onOptionsItemSelected method and perform any other function if you want
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
Toast.makeText(this, "back Button Clicked", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
Since you are using custom toolbar so you can easily use custom toolbar like this
toolbar.setNavigationIcon(R.drawable.back_arrow);// use your back arrow image
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(this,MainActivity.class));//call which activity you want in back press
finish();
}
});

Android Up button not working

I am trying to manually implement the actions that must take place when the up button on the actionbar is pressed but for some reason nothing happens when I press it.
here is my code:
public class ActivityOne extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_one);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar_actionbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Button button = (Button)findViewById(R.id.btn1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openActivityTwo();
}
});
Button button2 = (Button)findViewById(R.id.btn2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openActivityThree();
}
});
}
void openActivityTwo(){
Intent intent = new Intent(this, ActivityTwo.class);
startActivity(intent);
}
void openActivityThree(){
Intent intent = new Intent(this, ActivityThree.class);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_activity_one, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
else if(id == R.id.homeAsUp){
Log.i("","Up is pressed");
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
I understand that I have to explicitly assign a parent activity for the activity I want to implement up navigation on the manifest file, but problem is that this activity has multiple parents so I thought calling the finish() method when the up button is pressed on this activity will be the better approach.
I have already tried both id == R.id.home and id == R.id.homeAsUp and they both do not work. I do not know if it is because I am using AppCompactActivity or what Please help
Here is how you can implement this, try this code
use android.R.id.home instead of R.id.home or R.id.homeAsUp
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
//use onBackPressed() OR finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
The correct way to do it is to override public boolean onNavigateUp() just like overriding onBackPressed().
Using android studio 3.6.2 I've found that the Up button is not displayed by default in my apps, but it can be easily added..
Go to AndroidManifest.xml and update each activity that needs an Up button as follows:
<activity
android:name=".yourClassName"
android:parentActivityName=".MainActivity">
<meta-data android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.yourPackageName" />
</activity>
The target destination for the Up button is set by changing parentActivityName. In this example I have set it as '.MainActivity' but you can change that to whatever activity you want the user to navigate to.

How to have android action bar back button return to fragment

Hello all I have implemented a back button in the action bar in my app but I dont know how to return from an activity to a fragment or a fragment to fragment. so if someone could show me how to return from an activity to a fragment or even a fragment to another fragment that would be amazing. Here is the code i have right now
public class Article extends Activity{
private WebView webview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.articleview);
// etc...
getActionBar().setDisplayHomeAsUpEnabled(true);
Bundle b = getIntent().getExtras();
String KEY_LINK = b.getString("b");
String url = getIntent().getStringExtra("key");
WebView myWebView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl(url);
myWebView.loadUrl(KEY_LINK);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
and in my manifest I have
<activity
android:name=".Article"
android:label="#string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="com.NTCI.graffiti.Article" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.NTCI.graffiti.MainActivity" />
</activity>
but i want it to return to its host fragment not the main activity I have it set to. Any thoughts?
I recently had to do this and decided that a switch statement was the best way to go. Essentially you keep track of what fragment you're in now, and then switch to another one based on whatever criteria you set. For me, it was navigating back from one fragment to another.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
...
case android.R.id.home:
switch(currentFragment){
case FRAGMENT1:
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction
.replace(R.id.fragment_container, fragment2);
transaction.commit();
currentFragment = FRAGMENT_2;
return true;
default:
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction
.replace(R.id.fragment_container, fragment1);
transaction.commit();
currentFragment = FRAGMENT_1;
return true;
}
}
I'm assuming you mean you'd want to end the current activity you're in and display a fragment? In this case there'd probably be a parent FragmentActivity (to host the fragment), so you'd just end the current Activity and start another in the typical way. Once again:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
...
case android.R.id.home:
Intent intent = new Intent(this, NewFragmentActivity.class);
intent.putExtra(...); // so you can pass what activity you're coming from, if needed
startActivity(intent);
this.finish();
Keep in mind this is just a button and you're essentially assigning the onClick() action through case android.R.id.home:

Categories