【问题标题】:Button calles main activity from within the fragment按钮从片段中调用主要活动
【发布时间】:2016-08-17 08:31:28
【问题描述】:

我在菜单中添加了一个按钮,该按钮可以将我从片段带到主要活动,但我现在不知道如何实现它?

我在 onOptionsItemSelected 中放置了一个 switch 语句。 我将调用主要活动的片段:

  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);
 }

我的主要活动:

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);
       }
    }
 //
 }

你能帮忙吗?

编辑:这个片段与主活动相关联。我想用原始片段返回主活动。

【问题讨论】:

    标签: android android-fragments


    【解决方案1】:

    如果我没有正确回答您的问题,这就是您需要在 switch 语句中添加的内容,

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

    Intent的构造函数简述

    1. getActivity() 返回与片段关联的活动。 Activity 是一个上下文(因为 Activity 扩展了 Context)。
    2. MainActivity.class 是您要返回的活动。

    希望这会有所帮助! :)

    -更新问题后-

    我想这就是你要找的How to get a Fragment to remove itself?

    【讨论】:

    • 当我点击按钮时仍然没有任何反应..这可能是因为这个片段与主要活动相关联..但是我怎样才能回到主要活动中使用的主要片段..做我有道理吗?抱歉仍在尝试学习片段
    • -更新问题后-我认为这就是您要寻找的link
    • 感谢您的帮助。我已经尝试过,但是我在没有我需要的片段的情况下获得了主要的活动。删除当前片段后是否可以重新附加原始片段?
    • 我不知道这是否是一个明智的决定,但如果它对你有用并且如果你想保留这么多状态,为什么不使用dialog activity。只是一个建议。
    • 我通过从主活动调用 oncontactdelete 函数解决了这个问题。这可能不是最佳实践,但此功能可以满足我的要求。
    【解决方案2】:

    试试这个。(内部片段)

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

    【讨论】:

    • 我无法使用 getApplicationConetx,所以我将其替换为 getActivity.getapplicationContext()...当我点击按钮时没有任何反应:(
    【解决方案3】:

    你必须在你的itenselected选项中使用它

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

    context是你正在使用的fragment,next是你想要去的activity。

    【讨论】:

    • 我无法使用上下文,即使使用获取上下文也没有任何反应。反正谢谢
    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多