How to close a windows by call finish() in Fragment in android?

I created a Tabbed Activaity using Android Studio 1.2.2 wizard, I hope to close this window when I click the button btnClose, I write the code rootView.getContext().finish(); , but it's wrong, and PlaceholderFragmentOld.this.finish(); is wrong too.

How can I do? Thanks!

package; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import; import android.widget.Button; import; import info.dodata.messagecleanup.R; import bll.PublicParFun; import info.dodata.messagecleanup.R; public class PlaceholderFragmentOld extends Fragment { private AdView adView; public PlaceholderFragmentOld() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.cleanup_delete_fragment_old, container, false); adView=(AdView) rootView.findViewById(; PublicParFun.SetAD(adView); SetButtons(rootView); return rootView; } private void SetButtons(final View rootView){ rootView.findViewById( View.OnClickListener() { @Override public void onClick(View v) { rootView.getContext().finish(); } }); } }

package ui; import java.util.Locale; import; import; import; import; import; import; import android.os.Bundle; import; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import info.dodata.messagecleanup.R; import; import; import; import; public class CleanupDelete extends ActionBarActivity implements ActionBar.TabListener { SectionsPagerAdapter mSectionsPagerAdapter; ViewPager mViewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.cleanup_delete); final ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); mViewPager = (ViewPager) findViewById(; mViewPager.setAdapter(mSectionsPagerAdapter); mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } }); for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { actionBar.addTab( actionBar.newTab() .setText(mSectionsPagerAdapter.getPageTitle(i)) .setTabListener(this)); } } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { Fragment fragment; switch(position){ case 0: fragment = new PlaceholderFragmentOld(); break; case 1: fragment = new PlaceholderFragmentReduce(); break; case 2: fragment = new PlaceholderFragmentTrim(); break; case 3: fragment = new PlaceholderFragmentPerson(); break; default: throw new IllegalArgumentException("Invalid section number"); } return fragment; } @Override public int getCount() { return 4; } @Override public CharSequence getPageTitle(int position) { Locale l = Locale.getDefault(); switch (position) { case 0: return getString(R.string.Tab_Old); case 1: return getString(R.string.Tab_Reduce); case 2: return getString(R.string.Tab_Trim); case 3: return getString(R.string.Tab_Person); } return null; } } }


<?xml version="1.0" encoding="utf-8"?> < xmlns:android="" xmlns:tools="" android:id="@+id/pager" android:layout_width="match_parent" android:layout_height="match_parent" />


<RelativeLayout xmlns:android="" xmlns:tools="" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/border_ui" > <LinearLayout android:id="@+id/linearLayoutMain" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:paddingTop="20dip" android:paddingLeft="10dip" android:paddingRight="10dip" android:orientation="vertical" > <TextView android:id="@+id/tVDescription" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="2dip" style="@style/myTextDesciption" android:text="This is a descript"/> </LinearLayout> <LinearLayout android:id="@+id/linearLayoutToolBar" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:gravity="center" android:orientation="horizontal" android:layout_alignParentBottom="true" android:weightSum="4" > <Button android:id="@+id/btnDelete" style="@style/myTextMedium" android:layout_width="0dip" android:layout_height="fill_parent" android:layout_gravity="center" android:layout_weight="1" android:text="@string/BtnDelete" /> <Button android:id="@+id/btnClose" style="@style/myTextMedium" android:layout_width="0dip" android:layout_height="fill_parent" android:layout_gravity="center" android:layout_weight="1" android:text="@string/BtnClose" /> </LinearLayout> </RelativeLayout>

-------------Problems Reply------------

finish() can only be called in an Activity. Given that, you do it this way:

// Somewhere in your fragment

private void finishActivity() {
if(getActivity() != null) {

And you could then call that method to finish your Activity:

// Somewhere in your click listener


IMPORTANT: There is a possibility for getActivity() to return null. This is especially dangerous when the fragment is being detached from your Activity (when using a ViewPager or when you're juggling between numerous fragments in an activity). Calling it without checking will pose your code to the threat of NullPointerException.

You may do something like this.

public void onClick(View v) {

You should use getActivity().finish();

Category:android Views:5 Time:2018-12-18
Tags: android

Related post

  • how to open another window and close the window that calls it 2010-04-14

    I have this code in userpage.php: <script langauge="JavaScript"><!-- function newWindow(fileName,windowName) {,windowName); } //--></script> <a href="javascript:newWindow('1.html','window1')">Log

  • how to close main window(Dialog) in MFC 2011-01-21

    In MFC how to close main window(Dialog) when child window wm_close event is called --------------Solutions------------- I think you can post WM_CLOSE message to the main window in the child window's handler of WM_CLOSE. Like void ChildWindow::OnClose

  • HOW TO CLOSE A WINDOW IN LUMIA 520 2013-05-16

    HOW TO CLOSE A WINDOW IN LUMIA 520 --------------Solutions------------- If you're running Lumia Black then press and hold the back button and press the cross in the top corner to close it. If your not running black then continuously press the back bu

  • How do I remove Windows Live Call from Windows Xp Desktop Popup Menu? 2013-07-09

    I'm unable to remove Windows Live Call from my Windows Xp Desktop Popup Menu. Send me instructions on how to remove Windows Live Call from my WIndows Xp Desktop Popup Menu. See Screenshot. Screenshot: --------------Solutions------------- Hello again,

  • Windows 8 & IE 10 - how to close a window? 2014-12-09

    Windows 8 & IE 10 - how to close a window? I open a window, view the contents and then want to close it. How do I do it? I don't see any "x" close box in the upper right corner. --------------Solutions------------- Murray I assume you are using m

  • WPF MVVM: How to close a window 2010-12-07

    I have a button that closes my window when it's clicked: <Button x:Name="buttonOk" IsCancel="True">Ok</Button> That's fine until I add a command to the button i.e. <Button x:Name="buttonOk" Command="{Binding SaveCommand}" IsCancel="Tru

  • How To Close Unknown Window 2011-01-18

    all,, I have a project that is built in VB.Net 2010 and WPF 4. I have an option to return to a sign-in screen, yet this option can only be accessed from a separate (quit confirmation) window. This function can be called when one of about a hundred wi

  • Command line in Visual Studio - how to close popup window? 2011-02-17

    I have situation like below. I'm running some command and then I get a popup with Y/N answer. Is there a possibility to force answer Yes and automatically close the window through command line? --------------Solutions------------- If you want to clic

  • MFC-hosted WPF usercontrol how to close parent window on button press 2012-02-23

    I'm trying to get a legacy MFC application and a new WPF usercontrol to shut down a dialog window based on a button press in the WPF usercontrol. In essence, I would like some tips on how I can get the DoModal() function of MFC return. For various re

  • Give a windows handle (Native), how to close the windows using C#? 2012-03-01

    Given a handle of a window, how can I close the window by using the window handle? --------------Solutions------------- The easiest way is to use PInvoke and do a SendMessage with WM_CLOSE. [DllImport("user32.dll", CharSet = CharSet.Auto)] private st

  • How to close dialog window from viewmodel (Caliburn+WPF)? 2012-04-10

    I have ViewModel1 and View1 associated with it. I start dialog window from ViewModel2 (some another viewmodel) using IWindowManager object. The code from ViewModel2 class: windowManager.ShowDialog(new ViewModel()); So, I have Dialog Window with View1

  • how to close console window after form is closed 2012-04-21

    i have a console application project. it has gui (winforms) and console window which is used as debug console (application's run log). now, if i have got debug disabled i hide console window with ShowWindow native call. the problem is: after i close

  • How to close a window without confirm dialog? 2009-11-25

    window.close(); The above will pop up a confirm dialog each time, and not working at all in Firefox. --------------Solutions------------- I think that's not without a reason. People don't like windows being closed without notice. Closing a browser wi

  • How to close current window in jframe? 2010-11-19

    import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.JFrame; import class_program.NextPage; class Login extends JFrame implements ActionListener { JButton SUBMIT; JPanel panel; JLabel label1,label2; final JTextField te

  • How to close a 2010-12-29

    I know that you can close a with window.close but is there another way. I have a popup that opens facebook connect and i want to shut the popup whenever the user connects to facebook and then refresh the parent window...I thought in the p

  • How to close a window/activity after a certain amount of inactivity 2011-02-14

    I'm designing a music player app for Android that will feature pop-up controls. I'm currently trying to get these controls to close after a certain period of inactivity but there doesn't seem to be a clearly documented method of doing this. So far I

  • How to close a window programmatically in Cocoa Mac? 2011-04-08

    How can I programmatically close a window in cocoa mac ? I have opened a second window/xib from the first window/xib using button click. I need to close the first window/xib programmatically on opening or clicking the button. How can I do that? -----

  • ASP.NET MVC: How to close browser window instead of returning a view? 2011-05-27

    I have an instance where, not by my own choice, but I have a secondary popup window in the browser. Upon form submission back to a server-side MVC method, after this method is complete I'd like it to close that browser window that called it. Is there

  • How to close a window in GWT? 2011-09-09

    I have the next code to close a GWT window, but It doesn't work, could you tell me what's wrong or how to close a GWT window?. Thanks in advance: public native void closeBrowser() /*-{ $wnd.close(); }-*/; public void onModuleLoad() { Button cerrar =

  • How to close a window programmatically in 2011-10-24

    How can I close a window of external application programmatically in I just want to close the current window without closing the whole process. --------------Solutions------------- use FindWindow and SendMessage APIs here in C#, should be tri

  • How to close a window without closing the whole program? 2012-01-09

    in my application i have two forms let's say, LoginForm and AccountForm The LoginForm is set as the main Form, it is the form when the user is able to login from to his account ( two TEdits and login Button ). When a user type his login details and c

  • How to close several windows at once? 2012-08-12

    In windows XP I could ctrl-left-click several opened windows in the taskbar, then right-click and choose close, to close all windows at the same time. How do I do this in windows 7? Cheers, J. --------------Solutions------------- Hi Joshrob it is pos

  • How to close modal window on click of button in Embedded jsp 2015-07-16

    I am adding jsp in vaadin window as Embedded jsp = new Embedded(); jsp.setType(Embedded.TYPE_BROWSER); jsp.setSizeFull(); ExternalResource res=new ExternalResource("abc.jsp"); jsp.setSource(res); Window w1 = new Window(); w1.setModal(true); w1.setHei

  • How to close parent window on child window open using 2010-02-17

    Using javascript "window.close()" method after opening new window using "", it serve the problem i.e. but it will ask a confirmation message to user whether he really wants to close the window or not... if user selects yes then the parent

  • How to close a window (unload a NIB)? 2010-04-15

    I have a custom NSWindowController subclass that loads a NIB file during initialization like this: self = [super initWithNibNamed:@"myNib"]; if (self != nil) { [self window]; } The nib contains some custom views and some other controls. The NSWindowC

Copyright (C), All Rights Reserved.

processed in 0.175 (s). 11 q(s)