2016-04-23 5 views
0

Я добавил кнопку в меню, которое предположительно приведет меня от фрагмента к основному действию, но я не сейчас, как его реализовать?Кнопка вызывает основное действие изнутри фрагмента

Я положил оператор switch внутри onOptionsItemSelected. Фрагмент wehre я буду называть основной деятельностью:

public class DetailFragment extends Fragment 
    implements LoaderManager.LoaderCallbacks<Cursor> { 

    //Fragment detailFragment= new Fragment(this); 

    // callback methods implemented by MainActivity 
    public interface DetailFragmentListener { 
     void onContactDeleted(); // called when a contact is deleted 

     // pass Uri of contact to edit to the DetailFragmentListener 
    void onEditContact(Uri contactUri); 
    } 

    private static final int CONTACT_LOADER = 0; // identifies the Loader 

    private DetailFragmentListener listener; // MainActivity 
    private Uri contactUri; // Uri of selected contact 

    private TextView nameTextView; // displays contact's name 
    private TextView phoneTextView; // displays contact's phone 
    private TextView emailTextView; // displays contact's email 
    private TextView specialtyTextView; // displays contact's 
    private TextView cityTextView; // displays contact's city 
    private TextView chargeTextView; // displays contact's state 
    private TextView noteTextView; // displays contact's zip 
    private Button callButton; //Nuha 
    private Button emailButton; 
    private Button smsButton; 

    // set DetailFragmentListener when fragment attached 
    @Override 
    public void onAttach(Context context) { 
    super.onAttach(context); 
     listener = (DetailFragmentListener) context; 
    } 

     // remove DetailFragmentListener when fragment detached 
     @Override 
     public void onDetach() { 
     super.onDetach(); 
     listener = null; 
    } 

    // called when DetailFragmentListener's view needs to be created 
     @Override 
    public View onCreateView(
     LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 
    super.onCreateView(inflater, container, savedInstanceState); 
    setHasOptionsMenu(true); // this fragment has menu items to display 

    // get Bundle of arguments then extract the contact's Uri 
    Bundle arguments = getArguments(); 

    if (arguments != null) 
    contactUri = arguments.getParcelable(MainActivity.CONTACT_URI); 

    // inflate DetailFragment's layout 
    View view = 
      inflater.inflate(R.layout.fragment_detail, container, false); 

    // get the EditTexts 
    nameTextView = (TextView) view.findViewById(R.id.nameTextView); 
    phoneTextView = (TextView) view.findViewById(R.id.phoneTextView); 
    emailTextView = (TextView) view.findViewById(R.id.emailTextView); 
    specialtyTextView = (TextView) view.findViewById(R.id.specialtyTextView); 
    cityTextView = (TextView) view.findViewById(R.id.cityTextView); 
    chargeTextView = (TextView) view.findViewById(R.id.chargeTextView); 
    noteTextView = (TextView) view.findViewById(R.id.noteTextView); 
    callButton = (Button) view.findViewById(R.id.callbutton);//nuha 
    emailButton=(Button) view.findViewById(R.id.sendEmailbutton); 
    smsButton=(Button)view.findViewById(R.id.smsbutton); 
    // load the contact 
    getLoaderManager().initLoader(CONTACT_LOADER, null, this); 

    addListenerOnButton(view);//Nuha buttons 

    Animation animation = AnimationUtils.loadAnimation(getContext(),R.anim.pop_enter);//Animate details Nuha 
    nameTextView.startAnimation(animation); 
    phoneTextView.startAnimation(animation); 
    emailTextView.startAnimation(animation); 
    emailButton.startAnimation(animation); 
    specialtyTextView.startAnimation(animation); 
    cityTextView.startAnimation(animation); 
    chargeTextView.startAnimation(animation); 
    noteTextView.startAnimation(animation); 
    callButton.startAnimation(animation); 
    emailButton.startAnimation(animation);//till here 
    return view; 
    } 

    // display this fragment's menu items 
    @Override 
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { 
    super.onCreateOptionsMenu(menu, inflater); 
    inflater.inflate(R.menu.fragment_details_menu, menu); 
    } 

// handle menu item selections 
@Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
    switch (item.getItemId()) { 
    case R.id.action_edit: 
     listener.onEditContact(contactUri); // pass Uri to listener 
     return true; 
    case R.id.action_home:////home button 
     //What should I put here ?? 
     return true; 
    case R.id.action_delete: 
     deleteContact(); 
     return true; 
    } 

    return super.onOptionsItemSelected(item); 
} 

Мой mainactivity:

public class MainActivity extends AppCompatActivity 
    implements ContactsFragment.ContactsFragmentListener, 
DetailFragment.DetailFragmentListener, 
AddEditFragment.AddEditFragmentListener { 

// key for storing a contact's Uri in a Bundle passed to a fragment 
    public static final String CONTACT_URI = "contact_uri"; 

    private ContactsFragment contactsFragment; // displays contact list 

    // display ContactsFragment when MainActivity first loads 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 

    // if layout contains fragmentContainer, the phone layout is in use; 
    // create and display a ContactsFragment 
    if (savedInstanceState == null && 
    findViewById(R.id.fragmentContainer) != null) { 
    // create ContactsFragment 


    //Nuha animation 
    // add the fragment to the FrameLayout 
    ///Nuha try animation 
    FragmentManager fragmentManager = getSupportFragmentManager(); 
    FragmentTransaction transaction = fragmentManager.beginTransaction(); 
    transaction.setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.pop_enter, R.anim.pop_exit); 
    contactsFragment = new ContactsFragment(); 

    transaction.replace(R.id.fragmentContainer, contactsFragment); 
    transaction.addToBackStack(null); 
     transaction.commit(); 



     } 
     else { 
    contactsFragment = 
     (ContactsFragment) getSupportFragmentManager(). 
      findFragmentById(R.id.contactsFragment); 
     } 
    } 

    // display DetailFragment for selected contact 
    @Override 
    public void onContactSelected(Uri contactUri) { 
    if (findViewById(R.id.fragmentContainer) != null) // phone 
    displayContact(contactUri, R.id.fragmentContainer); 
    else { // tablet 
    // removes top of back stack 
    getSupportFragmentManager().popBackStack(); 

    displayContact(contactUri, R.id.rightPaneContainer); 
     } 
    } 

    // display AddEditFragment to add a new contact 
    @Override 
    public void onAddContact() { 
     if (findViewById(R.id.fragmentContainer) != null) // phone 
    displayAddEditFragment(R.id.fragmentContainer, null); 
     else // tablet 
    displayAddEditFragment(R.id.rightPaneContainer, null); 
     } 

    // display a contact 
    private void displayContact(Uri contactUri, int viewID) { 
    DetailFragment detailFragment = new DetailFragment(); 

    // specify contact's Uri as an argument to the DetailFragment 
    Bundle arguments = new Bundle(); 
    arguments.putParcelable(CONTACT_URI, contactUri); 
    detailFragment.setArguments(arguments); 

     // use a FragmentTransaction to display the DetailFragment 
     FragmentTransaction transaction = 
    getSupportFragmentManager().beginTransaction(); 
     transaction.replace(viewID, detailFragment); 
     transaction.addToBackStack(null); 
     transaction.commit(); // causes DetailFragment to display 
    } 

    // display fragment for adding a new or editing an existing contact 
    private void displayAddEditFragment(int viewID, Uri contactUri) { 
     AddEditFragment addEditFragment = new AddEditFragment(); 

     // if editing existing contact, provide contactUri as an argument 
     if (contactUri != null) { 
    Bundle arguments = new Bundle(); 
    arguments.putParcelable(CONTACT_URI, contactUri); 
    addEditFragment.setArguments(arguments); 
     } 

     // use a FragmentTransaction to display the AddEditFragment 
     FragmentTransaction transaction = 
    getSupportFragmentManager().beginTransaction(); 
     transaction.replace(viewID, addEditFragment); 
     transaction.addToBackStack(null); 
     transaction.commit(); // causes AddEditFragment to display 
    } 

    // return to contact list when displayed contact deleted 
    @Override 
    public void onContactDeleted() { 
     // removes top of back stack 
     getSupportFragmentManager().popBackStack(); 
     contactsFragment.updateContactList(); // refresh contacts 
    } 

    // display the AddEditFragment to edit an existing contact 
    @Override 
    public void onEditContact(Uri contactUri) { 
     if (findViewById(R.id.fragmentContainer) != null) // phone 
    displayAddEditFragment(R.id.fragmentContainer, contactUri); 

     else // tablet 
    displayAddEditFragment(R.id.rightPaneContainer, contactUri); 
    } 

    // update GUI after new contact or updated contact saved 
    @Override 
    public void onAddEditCompleted(Uri contactUri) { 
    // removes top of back stack 
    getSupportFragmentManager().popBackStack(); 
    contactsFragment.updateContactList(); // refresh contacts 

    if (findViewById(R.id.fragmentContainer) == null) { // tablet 
    // removes top of back stack 
    getSupportFragmentManager().popBackStack(); 

    // on tablet, display contact that was just added or edited 
    displayContact(contactUri, R.id.rightPaneContainer); 
     } 
    } 
// 
} 

Можете ли вы помочь?

Редактировать: Этот фрагмент связан с основным действием. Я хочу вернуться к основному действию с помощью исходного фрагмента.

ответ

1

Если я получаю ваш вопрос правильно, это то, что вам нужно положить в переключатель заявлении

Intent mainActivityIntent = new Intent(getActivity(),MainActivity.class); 
startActivity(mainActivityIntent); 

краткое объяснение конструктора Намерение

  1. getActivity() возвращает активность, связанную с фрагментом. Деятельность - это контекст (поскольку Activity расширяет контекст).
  2. MainActivity.class - это деятельность, которую вы хотите вернуть.

Надеюсь, это поможет! :)

-После вы обновили Вопрос-

Я думаю, это то, что вы ищете How to get a Fragment to remove itself?

+0

Все еще ничего не происходит, когда я нажимаю кнопку. Возможно, этот фрагмент связан с основным видом деятельности .. но как я могу вернуться к основному фрагменту, используемому в основном действии .. я имею в виду? извините, все еще пытаясь изучить фрагменты – NuhaAbd

+0

-После того как вы обновили вопрос, я думаю, что это то, что вы ищут [link] (http://stackoverflow.com/a/9387251/4382835) –

+0

Спасибо за помощь. Я пробовал, но я получаю основную деятельность без фрагмента, который мне нужен. исходный фрагмент после удаления текущего? – NuhaAbd

0

вы должны использовать это в itenselected вариант

Intent intent = new Intent(context, ActivityName.class); 
startActivity(intent); 

где контекст фрагмента, который вы используете, и следующий является деятельность, что вы хотите пойти.

+0

Я не могу использовать контекст и даже получить контекст ничего не случится. Thnks anyway – NuhaAbd

0

Попробуйте это. (Внутри фрагмента)

Intent intent = new Intent (getApplicationContext(),MainActivity.class); 
startActivity(intent); 
+0

Я не мог использовать getApplicationConetx, поэтому я заменил его getActivity.getapplicationContext() ... и ничего не происходит, когда я нажимаю кнопку :( – NuhaAbd

Смежные вопросы