Android:如何将我的活动变为片段

时间:2017-04-21 07:05:59

标签: android android-fragments android-activity android-fragmentactivity

我有这个Activity我想变成Fragment形式,所以我可以通过NavBar调用片段。可能吗?它很难解决这个问题。我有一个导航栏菜单,为每个选项调用片段,所以我真的需要将此代码转换为片段。

public class MainActivity extends ListActivity {
    private String URL_ITEMS = "http://192.168.1.88/asd/getFixture.php";
    private static final String TAG_FIXTURE = "fixture";
    private static final String TAG_MATCHID = "matchId";
    private static final String TAG_TEAMA = "teamA";
    private static final String TAG_TEAMB = "teamB";
    JSONArray matchFixture = null;
    ArrayList<HashMap<String, String>> matchFixtureList = new ArrayList<HashMap<String, String>>();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Call Async task to get the match fixture
        new GetFixture().execute();
    }
    private class GetFixture extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
        @Override
        protected Void doInBackground(Void... arg) {
            ServiceHandler serviceClient = new ServiceHandler();
            Log.d("url: ", "> " + URL_ITEMS);
            String json = serviceClient.makeServiceCall(URL_ITEMS,ServiceHandler.GET);
            // print the json response in the log
            Log.d("Get match fixture response: ", "> " + json);
            if (json != null) {
                try {
                    Log.d("try", "in the try");
                    JSONObject jsonObj = new JSONObject(json);
                    Log.d("jsonObject", "new json Object");
                    // Getting JSON Array node
                    matchFixture = jsonObj.getJSONArray(TAG_FIXTURE);
                    Log.d("json aray", "user point array");
                    int len = matchFixture.length();
                    Log.d("len", "get array length");
                    for (int i = 0; i < matchFixture.length(); i++) {
                        JSONObject c = matchFixture.getJSONObject(i);
                        String matchId = c.getString(TAG_MATCHID);
                        Log.d("matchId", matchId);
                        String teamA = c.getString(TAG_TEAMA);
                        Log.d("teamA", teamA);
                        String teamB = c.getString(TAG_TEAMB);
                        Log.d("teamB", teamB);
                        //  hashmap for single match
                        HashMap<String, String> matchFixture = new HashMap<String, String>();
                        // adding each child node to HashMap key => value
                        matchFixture.put(TAG_MATCHID, matchId);
                        matchFixture.put(TAG_TEAMA, teamA);
                        matchFixture.put(TAG_TEAMB, teamB);
                        matchFixtureList.add(matchFixture);
                    }
                }
                catch (JSONException e) {
                    Log.d("catch", "in the catch");
                    e.printStackTrace();
                }
            } else {
                Log.e("JSON Data", "Didn't receive any data from server!");
            }
            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            ListAdapter adapter = new SimpleAdapter(
                    MainActivity.this, matchFixtureList,
                    R.layout.list_item, new String[] {
                    TAG_MATCHID, TAG_TEAMA,TAG_TEAMB
            }
                    , new int[] {
                    R.id.matchId,R.id.teamA,
                    R.id.teamB
            }
            );
            setListAdapter(adapter);
        }
    }

2 个答案:

答案 0 :(得分:0)

您必须更改代码才能在片段中使用。这并不难。

public void onCreate(Bundle savedInstanceState) {
    new GetFixture().execute();

    super.onCreate(savedInstanceState);

}

然后createView for fragment

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    data = new ArrayList<PlacesModel>();

    View rootView = inflater.inflate(R.layout.defaultfragment, container, false);

    return rootView;
}

然后您的异步类将与上面相同。在获取任何视图元素的引用时,只需使用rootView.findViewById()

检查此tutorial以便更好地理解。

答案 1 :(得分:0)

我为你改变了。

import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class MainFragment extends Fragment {
    private String URL_ITEMS = "http://192.168.1.88/asd/getFixture.php";
    private static final String TAG_FIXTURE = "fixture";
    private static final String TAG_MATCHID = "matchId";
    private static final String TAG_TEAMA = "teamA";
    private static final String TAG_TEAMB = "teamB";
    JSONArray matchFixture = null;
    ArrayList<HashMap<String, String>> matchFixtureList = new ArrayList<HashMap<String, String>>();


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_main, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // Call Async task to get the match fixture
        new GetFixture().execute();
    }


    private class GetFixture extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... arg) {
            ServiceHandler serviceClient = new ServiceHandler();
            Log.d("url: ", "> " + URL_ITEMS);
            String json = serviceClient.makeServiceCall(URL_ITEMS, ServiceHandler.GET);
            // print the json response in the log
            Log.d("Get match fixture response: ", "> " + json);
            if (json != null) {
                try {
                    Log.d("try", "in the try");
                    JSONObject jsonObj = new JSONObject(json);
                    Log.d("jsonObject", "new json Object");
                    // Getting JSON Array node
                    matchFixture = jsonObj.getJSONArray(TAG_FIXTURE);
                    Log.d("json aray", "user point array");
                    int len = matchFixture.length();
                    Log.d("len", "get array length");
                    for (int i = 0; i < matchFixture.length(); i++) {
                        JSONObject c = matchFixture.getJSONObject(i);
                        String matchId = c.getString(TAG_MATCHID);
                        Log.d("matchId", matchId);
                        String teamA = c.getString(TAG_TEAMA);
                        Log.d("teamA", teamA);
                        String teamB = c.getString(TAG_TEAMB);
                        Log.d("teamB", teamB);
                        //  hashmap for single match
                        HashMap<String, String> matchFixture = new HashMap<String, String>();
                        // adding each child node to HashMap key => value
                        matchFixture.put(TAG_MATCHID, matchId);
                        matchFixture.put(TAG_TEAMA, teamA);
                        matchFixture.put(TAG_TEAMB, teamB);
                        matchFixtureList.add(matchFixture);
                    }
                } catch (JSONException e) {
                    Log.d("catch", "in the catch");
                    e.printStackTrace();
                }
            } else {
                Log.e("JSON Data", "Didn't receive any data from server!");
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            ListAdapter adapter = new SimpleAdapter(
                    MainFragment.this.getActivity(), matchFixtureList,
                    R.layout.list_item, new String[]{
                    TAG_MATCHID, TAG_TEAMA, TAG_TEAMB
            }
                    , new int[]{
                    R.id.matchId, R.id.teamA,
                    R.id.teamB
            }
            );
            setListAdapter(adapter);
        }
    }
}

从任何活动中使用此方法显示片段:

private void showFragment(Fragment fragment) {
    FragmentManager fm = getFragmentManager();
    fm.beginTransaction()
            .setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
            .show(fragment)
            .addToBackStack(null)
            .commit();
}