2014-02-09 151 views
0

我正在慢慢地將我的應用程序轉換爲片段vs活動,此刻我正在收到一些奇怪的行爲。我有一個按鈕,當按下時應該加載一個新的片段到視圖中,然後執行一個異步任務,以便將信息加載到片段中。片段不被替換,放在其他片段頂部

我對其中包含該按鈕的片段,以交換新的片斷代碼:

public class Discover extends Fragment { 
    Fragment Fragment_one; 

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

     View v = inflater.inflate(R.layout.activity_discover, container, false); 

     SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); 
     String userName = prefs.getString("userName", null); 
     String userID = prefs.getString("userID", null); 

     //add button onclick programatically 
     Button bt = (Button)v.findViewById(R.id.discoverBeers); 
     bt.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // do whatever stuff you wanna do here 
       FragmentManager man=getFragmentManager(); 
       FragmentTransaction tran=man.beginTransaction(); 
       Fragment_one=new BPTopBeers(); 
       tran.add(R.id.main, Fragment_one);//tran. 
       tran.addToBackStack(null); 
       tran.commit(); 
      } 
     }); 

     // Inflate the layout for this fragment 
     //todo: change to discover layout 
     return v; 

    } 

我知道它裝在另一個片段的頂部,而不是交換,因爲我可以看到它下面的另一個片段:

enter image description here

,其在按鈕上點擊加載的片段是:

public class BPTopBeers extends Fragment { 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     View v = inflater.inflate(R.layout.toptaste_layout, container, false); 

     SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); 
     String userName = prefs.getString("userName", null); 
     String userID = prefs.getString("userID", null); 

     String title = "Top Beers on Beer Portfolio"; 
     TextView topTitle = (TextView) v.findViewById(R.id.topTasteTitle); 
     topTitle.setText(title); 


     //construct url 
     String url = "myURL"; 

     Log.d("myUrl", url); 

     //async task goes here 
     new GetYourTopTasteBeers(getActivity()).execute(url); 

     // Inflate the layout for this fragment 

     return v; 

    } 

和被稱爲該分段異步任務看起來是這樣的:

public class GetYourTopTasteBeers extends AsyncTask<String, Void, String> { 

    Context c; 
    private ProgressDialog Dialog; 

    public GetYourTopTasteBeers (Context context) 
    { 
     c = context; 
     Dialog = new ProgressDialog(c); 
    } 

    @Override 
    protected String doInBackground(String... arg0) { 
     // TODO Auto-generated method stub 
     return readJSONFeed(arg0[0]); 
    } 

    protected void onPreExecute() { 
     Dialog.setMessage("Getting beers"); 

     Dialog.setTitle("Loading"); 
     Dialog.setCancelable(false); 
     Dialog.show(); 
    } 

    protected void onPostExecute(String result){ 
     //decode json here 
     try{ 
      JSONArray jsonArray = new JSONArray(result); 


      //acces listview 
      ListView lv = (ListView) ((Activity) c).findViewById(R.id.topTasteBeers); 

      //make array list for beer 
      final List<ShortBeerInfo> tasteList = new ArrayList<ShortBeerInfo>(); 



      for(int i = 0; i < jsonArray.length(); i++) { 

       String beer = jsonArray.getJSONObject(i).getString("beer"); 
       String rate = jsonArray.getJSONObject(i).getString("rate"); 
       String beerID = jsonArray.getJSONObject(i).getString("id"); 
       String breweryID = jsonArray.getJSONObject(i).getString("breweryID"); 


       int count = i + 1; 

       beer = count + ". " + beer; 


       //create object 
       ShortBeerInfo tempTaste = new ShortBeerInfo(beer, rate, beerID , breweryID); 

       //add to arraylist 
       tasteList.add(tempTaste); 


       //add items to listview 
       ShortBeerInfoAdapter adapter1 = new ShortBeerInfoAdapter(c ,R.layout.brewer_stats_listview, tasteList); 
       lv.setAdapter(adapter1); 

       //set up clicks 
       lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
        @Override 
        public void onItemClick(AdapterView<?> arg0, View arg1, 
              int arg2, long arg3) { 
         ShortBeerInfo o=(ShortBeerInfo)arg0.getItemAtPosition(arg2); 

         String tempID = o.id; 
         String tempBrewID = o.brewery; 

         Toast toast = Toast.makeText(c, tempID, Toast.LENGTH_SHORT); 
         toast.show(); 

         //todo: change fragment to beer page 

         //Intent myIntent = new Intent(c, BeerPage2.class); 
         //myIntent.putExtra("id", tempID); 
         //myIntent.putExtra("breweryID", tempBrewID); 
         //c.startActivity(myIntent); 


        } 
       }); 




      } 

     } 
     catch(Exception e){ 

     } 

     Dialog.dismiss(); 

    } 

    public String readJSONFeed(String URL) { 
     StringBuilder stringBuilder = new StringBuilder(); 
     HttpClient httpClient = new DefaultHttpClient(); 
     HttpGet httpGet = new HttpGet(URL); 
     try { 
      HttpResponse response = httpClient.execute(httpGet); 
      StatusLine statusLine = response.getStatusLine(); 
      int statusCode = statusLine.getStatusCode(); 
      if (statusCode == 200) { 
       HttpEntity entity = response.getEntity(); 
       InputStream inputStream = entity.getContent(); 
       BufferedReader reader = new BufferedReader(
         new InputStreamReader(inputStream)); 
       String line; 
       while ((line = reader.readLine()) != null) { 
        stringBuilder.append(line); 
       } 
       inputStream.close(); 
      } else { 
       Log.d("JSON", "Failed to download file"); 
      } 
     } catch (Exception e) { 
      Log.d("readJSONFeed", e.getLocalizedMessage()); 
     } 
     return stringBuilder.toString(); 
    } 

} 
+0

顯示您的佈局文件 –

+1

嘗試替換而不是添加 – Raghunandan

回答

1

當您使用add它只是直的片段添加到視圖然而,當您使用replace它刪除當前的片段,然後添加這就是你正在尋找的,因爲它出現在您的XML沒有被設置爲match_parent

0

可以隱藏舊片段,如果你想返回到前

fragmentManager 
      .beginTransaction() 
      .hide(previous fragment) 
      .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) 
      .add(R.id.content_frame, newFragment, 
       ParserConstants.FRAGMENT_MAIN).addToBackStack(null) 
      .commitAllowingStateLoss(); 
+0

如果我想要添加後退按鈕功能,我會使用此回退片段嗎? – Mike

+0

如果你按下返回按鈕 - 你回到上一個 –