方向更改后按钮和菜单停止工作

时间:2014-03-05 17:39:10

标签: java android android-fragments android-activity mobile-application

我有一个Android应用,它使用标签和片段进行导航。该应用程序在启动时工作正常,但在我更改方向后,菜单项和片段中的小部件停止工作。如果我放,该应用程序可以工作     android:configChanges="orientation|screenSize" 在清单中,但在Android文档中它说这应该是最后的手段,所以我想知道是否有更好的解决方案。这是主机活动的代码和其中一个片段。

package com.mynews;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.Menu;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        //stopService(new Intent(this, FindArticlesService.class));
        ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        Tab tab = actionBar.newTab()
                .setText("Articles")
                .setTabListener(new TabListener<Articles>(this, "articles", Articles.class));
        actionBar.addTab(tab);
        tab = actionBar.newTab()
                .setText("Websites")
                .setTabListener(new TabListener<UserSites>(this, "websites", UserSites.class));
        actionBar.addTab(tab);
        tab = actionBar.newTab()
                .setText("Add a website")
                .setTabListener(new TabListener<AddSites>(this, "add a site", AddSites.class));
        actionBar.addTab(tab);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        //getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        ////Intent intent = new Intent(this, FindArticlesService.class);
        //this.startService(intent);
    }

    public static class TabListener<T extends Fragment> implements ActionBar.TabListener {
        Fragment fragment;
        final Activity activity;
        final String tag;
        final Class<T> mClass;

        public TabListener(Activity a, String s, Class<T> c){
            activity = a;
            tag = s;
            mClass = c;
        }

        @Override
        public void onTabReselected(Tab tab, FragmentTransaction ft) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            // TODO Auto-generated method stub
            if(fragment == null){
                fragment = Fragment.instantiate(activity, mClass.getName());
                ft.add(android.R.id.content, fragment, tag);
            }else{
                ft.attach(fragment);
            }
        }

        @Override
        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
            // TODO Auto-generated method stub
            if(fragment != null){
                ft.detach(fragment);
            }
            activity.closeContextMenu();
        }

    }

}

My Fragment Class

 package com.mynews;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.MalformedURLException;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AddSites extends Fragment {

    public AddSites(){}

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_add_sites);
        // Show the Up button in the action bar.
        setHasOptionsMenu(true);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        Button button = (Button) getActivity().findViewById(R.id.add);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                UserSitesFunc usf = new UserSitesFunc(); //create a new UserSitesFunc to hold
                try{                                    //the list of sites
                    FileInputStream fis = getActivity().openFileInput("MySites.ser");//check if there's a file
                    ObjectInputStream ois = new ObjectInputStream(fis);//with a USF object
                    usf = (UserSitesFunc) ois.readObject(); //if there is, deserialize it and use it
                    ois.close();//instead of a brand new object
                }catch(IOException e){ //catch various exceptions
                    e.printStackTrace();
                }catch(Exception ep){
                    ep.printStackTrace();
                }finally{
                try{ //do this with either the new object or the deserialised one
                    EditText website = (EditText) getActivity().findViewById(R.id.editText1);//get the input
                    EditText keywords = (EditText) getActivity().findViewById(R.id.editText2);//from the user
                    String web = website.getText().toString(); //store it in strings
                    String key = keywords.getText().toString();
                    String[] kwords = key.split(", ");
                    ArrayList<String> newKeywords = new ArrayList<String>();
                    for(String s:kwords){
                        newKeywords.add(s);
                    }
                    Sites s = new Sites(web, newKeywords);//create a new site from the input
                    if(usf.siteList.contains(s)){
                        showContainedDialog();
                        return;
                    }
                    usf.addSite(s);//add it to the user's list of sites
                    FileOutputStream fs = getActivity().openFileOutput("MySites.ser", Context.MODE_PRIVATE);//save it
                    ObjectOutputStream oos = new ObjectOutputStream(fs);
                    oos.writeObject(usf);
                    oos.close();
                    Toast.makeText(getActivity(), web + " added to Tracked Websites", Toast.LENGTH_LONG).show();
                    website.setText("");
                    keywords.setText("");
                }catch(MalformedURLException mue){
                    showDialog();
                }catch(Exception ex){
                    ex.printStackTrace();
                }
                }
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View view = inflater.inflate(R.layout.activity_add_sites, container, false);
        return view;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.clear();
        inflater.inflate(R.menu.add_sites, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            // This ID represents the Home or Up button. In the case of this
            // activity, the Up button is shown. Use NavUtils to allow users
            // to navigate up one level in the application structure. For
            // more details, see the Navigation pattern on Android Design:
            //
            // http://developer.android.com/design/patterns/navigation.html#up-vs-back
            //
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public static class NotAWebsiteDialog extends DialogFragment {
        public static NotAWebsiteDialog newInstance(){
            NotAWebsiteDialog notAWebsite = new NotAWebsiteDialog();
            Bundle args = new Bundle();
            notAWebsite.setArguments(args);
            return notAWebsite;
        }

        @Override
        public Dialog onCreateDialog(final Bundle savedInstanceState) {
            // TODO Auto-generated method stub
             return new AlertDialog.Builder(getActivity())
             .setMessage("Please enter a vaild web address")
             .create();

        }
    }

    public void showDialog(){
        DialogFragment dialog = NotAWebsiteDialog.newInstance();
        dialog.show(getFragmentManager(), "Not A Website");
    }

    public static class AlreadyContainsWebsiteDialog extends DialogFragment {
        public static AlreadyContainsWebsiteDialog newInstance(){
            AlreadyContainsWebsiteDialog containsAWebsite = new AlreadyContainsWebsiteDialog();
            Bundle args = new Bundle();
            containsAWebsite.setArguments(args);
            return containsAWebsite;
        }

        @Override
        public Dialog onCreateDialog(final Bundle savedInstanceState) {
            // TODO Auto-generated method stub
             return new AlertDialog.Builder(getActivity())
             .setMessage("This website is already being tracked")
             .create();

        }
    }

    public void showContainedDialog(){
        DialogFragment dialog = AlreadyContainsWebsiteDialog.newInstance();
        dialog.show(getFragmentManager(), "Contains this Website");
    }

}

1 个答案:

答案 0 :(得分:0)

感谢你不采取简单的方法......继续你的编程工作!

有关Menus及其宿主片段的使用,请参阅my answer here