如何从另一个活动加载以前的片段

时间:2014-01-07 10:24:09

标签: android android-fragments

我正在开发一个应用程序,用于从Web服务获取一些数据并将它们显示到列表视图中。它运作正常。现在我在我的应用程序中包含了一个导航抽屉。首先,用户必须登录。之后,它将进入导航抽屉出现的主屏幕。我不知道碎片,但不知怎的,我已经实现了它来处理导航抽屉上的点击事件。在我的第一次尝试中,我无法使用我的应用程序[包括导航抽屉后]正确处理点击事件。但不知怎的,我也做到了..

我的问题是,当我点击片段中的一个按钮时,它会转到正确的活动,但是当我按下它时,它不会转到我之前可用的导航抽屉片段。

我该如何处理?

以下是我的代码:

public class NavHomeFragment extends Fragment  {


    public static String url ="my url;
   // public static String url ="my url";

    public static  String confirm;
    static String firstName;
    public static String ActualImage;
    static final String TAG_DATA = "d";
    static final String TAG_OBJ_1 = "Appointment";
    static final String TAG_OBJ_2 = "PatientProfile";
    static final String TAG_PROP_FNAME = "FirstName";
    static final String TAG_PROP_LNAME = "LastName";
    static final String TAG_STIME = "StartTime";
    static final String TAG_ETIME = "EndTime";
    static final String TAG_DATE = "Date";
    static final String TAG_HID = "PatientPersonId";
    static final String TAG_HIDApp = "AppointmentId";
    static final String TAG_IMG = "ImageURL";
    public static ArrayList<HashMap<String, String>> oslist;  


    JSONArray androids = null;
    JSONObject duplicate;
   public static JSONArray dupArray;


   public JSONArray getJsonArray() {
        return dupArray;
    }


 public NavHomeFragment()
 {

 }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        oslist = new ArrayList<HashMap<String, String>>();
        View rootView = inflater.inflate(R.layout.vardle_home, container, false);
        TextView tx = (TextView) rootView.findViewById(R.id.txtrequestCount);  



       tx.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                if(MotionEvent.ACTION_UP == event.getAction()){

                    //Home hm = new Home();
                    new JSONParse().execute();


                   // Toast.makeText(getActivity(), "Hello", Toast.LENGTH_LONG).show();
                }


                return false;
            }
        });

        return rootView;    


    }  


    public  class JSONParse extends AsyncTask<String, String, JSONObject> {
        private ProgressDialog pDialog;

       public JSONParse(){

        }
       @Override
       protected void onPreExecute() {
           super.onPreExecute();
           /*fname = (TextView)findViewById(R.id.fname);
           lname = (TextView)findViewById(R.id.lname);
           stime = (TextView)findViewById(R.id.stime);
           etime = (TextView)findViewById(R.id.etime);
           date = (TextView)findViewById(R.id.blank);*/
           pDialog = new ProgressDialog(getActivity());
           pDialog.setMessage("Getting Data ...");
           pDialog.setIndeterminate(false);
           pDialog.setCancelable(true);
           pDialog.show();

       }


       @Override
        public JSONObject doInBackground(String... arg0) {
        // TODO Auto-generated method stub
           JsonParser jParser = new JsonParser();

           // Getting JSON from URL
           JSONObject json = null;
        try {

            JSONObject parm = new JSONObject();
            //parm.put("PersonID", confirm);
            parm.put("caregiverPersonId", MainActivity.confirm);
            json = jParser.getJSONFromUrl(parm,url);

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            //Toast.makeText(getApplicationContext(), "Hi "+firstName+"You Don't Have Any Requests!", Toast.LENGTH_LONG).show();
        }
           return json;

    }


       @Override
    public void onPostExecute(JSONObject json) {
        // TODO Auto-generated method stub

          // String imgUrl = null;
           try {
                  // Getting JSON Array from URL
               //JSONObject jobs  = json.getJSONObject(TAG_DATA);

               String emptyjson = json.getString(TAG_DATA);

               if(emptyjson.equals("[]")){

                   startActivity(new Intent(getActivity(),Empty.class));
               }
               else
               {

               androids = json.getJSONArray(TAG_DATA);


                //JSONObject appt= new JSONObject(json.getString("d"));


               for(int i = 0; i < androids.length(); i++){
                   ActualImage = "null";
                  JSONObject c = androids.getJSONObject(i);

                  // Storing  JSON item in a Variable

                  JSONObject toHid = c.getJSONObject(TAG_OBJ_1);

                  String Hid = toHid.getString(TAG_HID);

                  JSONObject job  = c.getJSONObject(TAG_OBJ_2);

                  String url = job.getString("ImageURL");

                  //String url = "null";


                  if(!url.equalsIgnoreCase("null")){

                      if(!url.equalsIgnoreCase("") ) {

                          String newUrl =  url.substring(3); 
                          ActualImage = "http://vardle.paragoncmb.com"+newUrl;
                        //  ActualImage = "http://qa.vardle.com"+newUrl;
                      }


                  }


                  else{
                      ActualImage = null; 
                  }



                  firstName = job.getString(TAG_PROP_FNAME);
                  String lastName = job.getString(TAG_PROP_LNAME);

                  JSONObject job_two  = c.getJSONObject(TAG_OBJ_1).getJSONObject("DayTimeSlot");

                  String start = job_two.getString(TAG_STIME );
                  String end = job_two.getString(TAG_ETIME);

                /*  String ackwardDate = job_two.getString(TAG_DATE);;
                  Calendar calendar = Calendar.getInstance();
                  String ackwardRipOff = ackwardDate.replace("/Date(", "").replace(")/", "");
                  Long timeInMillis = Long.valueOf(ackwardRipOff);
                  calendar.setTimeInMillis(timeInMillis);
                  String theDate = (calendar.getTime().toGMTString());
                  */
                  String Ldate = job_two.getString(TAG_DATE);
                  String ackwardRipOff = Ldate.replace("/Date(", "").replace(")/", "");
                  Long Ldat = Long.valueOf(ackwardRipOff);
                  Date date = new Date(Ldat);
                  String strdate = (String) DateFormat.format("MM/dd/yy", date);

                  //String date = dateConvert(Ldate);
                  //long Ldate = job_two.getLong("Date");

                  //String strdate = (String) DateFormat.format("MM/dd/yy h:mmaa", date);

                  JSONObject job_three  = c.getJSONObject(TAG_OBJ_1);
                  String AppoinmentID =  job_three.getString(TAG_HIDApp);

                  // Adding value HashMap key => value

                  HashMap<String, String> map = new HashMap<String, String>();

                  map.put(MainActivity.TAG_PROP_FNAME, firstName);
                  map.put(MainActivity.TAG_PROP_LNAME, lastName);
                  map.put(MainActivity.TAG_STIME , start);
                  map.put(MainActivity.TAG_ETIME, end);
                  map.put(MainActivity.TAG_DATE, strdate);
                  map.put(MainActivity.TAG_HID, Hid);
                  map.put("ImageURL", ActualImage);
                  map.put("AppointmentId", AppoinmentID);

                  oslist.add(map);

                  //duplicate = new JSONObject();

                  Intent reult = new Intent(getActivity(),ViewList.class);
                  //reult.putStringArrayListExtra("map", oslist);
                  //startActivity(reult);


                  reult.putExtra("arraylist", oslist);
                  startActivityForResult(reult, 500);

                  }

               dupArray = new JSONArray();
               dupArray.put(oslist);
               }

                } catch (JSONException e) {
                    e.printStackTrace();
              //Intent reult = new Intent(MainActivity.this,ViewList.class);
              //reult.putStringArrayListExtra("map", oslist);
             // startActivity(reult);

          }

           pDialog.dismiss();
       }

  }

}

这是导航抽屉的类

public class NavigationActivity extends Activity{

private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;

// nav drawer title
private CharSequence mDrawerTitle;

// used to store app title
private CharSequence mTitle;

// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;

private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.nav_list);

    mTitle = mDrawerTitle = getTitle();

    // load slide menu items
    navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

    // nav drawer icons from resources
    navMenuIcons = getResources()
            .obtainTypedArray(R.array.nav_drawer_icons);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

    navDrawerItems = new ArrayList<NavDrawerItem>();

    // adding nav drawer items to array
    // Home
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
    // Find People
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
    // Photos
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
    // Communities, Will add a counter here
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "22"));
    // Pages
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
    // What's hot, We  will add a counter here
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));


    // Recycle the typed array
    navMenuIcons.recycle();

    mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

    // setting the nav drawer list adapter
    adapter = new NavDrawerListAdapter(getApplicationContext(),
            navDrawerItems);
    mDrawerList.setAdapter(adapter);

    // enabling action bar app icon and behaving it as toggle button
    getActionBar().setDisplayHomeAsUpEnabled(true);
    getActionBar().setHomeButtonEnabled(true);

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
            R.drawable.ic_drawer, //nav menu toggle icon
            R.string.app_name, // nav drawer open - description for accessibility
            R.string.app_name // nav drawer close - description for accessibility
    ) {
        public void onDrawerClosed(View view) {
            getActionBar().setTitle(mTitle);
            // calling onPrepareOptionsMenu() to show action bar icons
            invalidateOptionsMenu();
        }

        public void onDrawerOpened(View drawerView) {
            getActionBar().setTitle(mDrawerTitle);
            // calling onPrepareOptionsMenu() to hide action bar icons
            invalidateOptionsMenu();
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    if (savedInstanceState == null) {
        // on first time display view for first nav item
        displayView(0);
    }
}

/**
 * Slide menu item click listener
 * */
private class SlideMenuClickListener implements
        ListView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        // display view for selected nav drawer item
        displayView(position);
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // toggle nav drawer on selecting action bar app icon/title
    if (mDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }
    // Handle action bar actions click
    switch (item.getItemId()) {
    case R.id.action_settings:
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

/* *
 * Called when invalidateOptionsMenu() is triggered
 */
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    // if nav drawer is opened, hide the action items
    boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
    menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
    return super.onPrepareOptionsMenu(menu);
}

/**
 * Diplaying fragment view for selected nav drawer list item
 * */
private void displayView(int position) {
    // update the main content by replacing fragments
    Fragment fragment = null;
    switch (position) {
    case 0:
        fragment = new NavHomeFragment();
        break;
    case 1:
        fragment = new FindPeopleFragment();
        break;
    /*case 2:
        fragment = new PhotosFragment();
        break;
    case 3:
        fragment = new CommunityFragment();
        break;
    case 4:
        fragment = new PagesFragment();
        break;
    case 5:
        fragment = new WhatsHotFragment();
        break;*/

    default:
        break;
    }

    if (fragment != null) {
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.frame_container, fragment).commit();

        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        mDrawerList.setSelection(position);
        setTitle(navMenuTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    } else {
        // error in creating fragment
        Log.e("MainActivity", "Error in creating fragment");
    }
}

@Override
public void setTitle(CharSequence title) {
    mTitle = title;
    getActionBar().setTitle(mTitle);
}

/**
 * When using the ActionBarDrawerToggle, you must call it during
 * onPostCreate() and onConfigurationChanged()...
 */

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    // Sync the toggle state after onRestoreInstanceState has occurred.
    mDrawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Pass any configuration change to the drawer toggls
    mDrawerToggle.onConfigurationChanged(newConfig);
}

}

这是在单击片段上的按钮后运行的类。从视觉上来说它是列表视图。这里显示的数据是通过调用Web服务。

public class ViewList extends Activity {

    private static final String TAG_VER = "ver";
    private static final String TAG_NAME = "name";
    private static final String TAG_API = "api";

    ListView list;
    NewsRowAdapter adapter;
    ArrayList<HashMap<String, String>> arl;
    ArrayList<HashMap<String, String>> empty;

    public ViewList()
    {

    }


@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    ActionBar actionBar = getActionBar();

    actionBar.setDisplayHomeAsUpEnabled(true);



        setContentView(R.layout.activity_main);

         arl = (ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("arraylist");

        list  =(ListView)findViewById(R.id.list);




        adapter  = new NewsRowAdapter(getBaseContext(),ViewList.this, R.layout.row, arl);
        /*if(adapter.getCount()!=0){
            list.setAdapter(adapter);
       }*/
       /*else{
           AlertDialog.Builder builder = new AlertDialog.Builder(this);
           builder.setMessage("Search is empty")
            .setCancelable(true)
            .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                     dialog.cancel();
                }
            });
           AlertDialog alert = builder.create();
       }
        */
        list.setAdapter(adapter);
       // setListAdapter(adapter);



}

public void handleImage(String url,ImageView im){
    if(url.equalsIgnoreCase("null")){
        Bitmap bImage = BitmapFactory.decodeResource(getResources(), R.drawable.propic);
        im.setImageBitmap(bImage);
    }
}

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    super.onBackPressed();
    this.finishAffinity();
    startActivity(new Intent(ViewList.this,NavHomeFragment.class));



}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // TODO Auto-generated method stub

    MenuInflater infl = getMenuInflater();

    infl.inflate(R.menu.activity_main_actions, menu);


    return super.onCreateOptionsMenu(menu);



}

}

请指导我实现这一目标。如果有人会用一些例子指导我,我会很高兴:)

1 个答案:

答案 0 :(得分:0)

使用“FLAG_ACTIVITY_CLEAR_TOP”标记开始您的活动。

Intent intent = new Intent(this,ViewList.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);