片段未被替换,被放置在其他片段的顶部

时间:2014-02-09 16:57:13

标签: android android-fragments android-asynctask

我正在慢慢将我的应用程序转换为片段与活动,我现在得到一些奇怪的行为。我有一个按钮,按下时应该将一个新片段加载到视图中,然后执行异步任务,以便将信息加载到片段中。

我的代码片段包含交换新片段的按钮:

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

}

2 个答案:

答案 0 :(得分:1)

当您使用add时,只需将片段直接添加到视图中,但是当您使用replace时,它会删除当前片段,然后添加新的片段,这是您要查找的内容,因为它看起来是您的XML未设置为match_parent

答案 1 :(得分:0)

如果要返回上一页

,可以隐藏旧片段
fragmentManager
            .beginTransaction()
            .hide(previous fragment)
            .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
            .add(R.id.content_frame, newFragment,
                ParserConstants.FRAGMENT_MAIN).addToBackStack(null)
            .commitAllowingStateLoss();