0

我正在尝试将一些自定义列表适配器放入他们自己的类中,以使我的应用程序具有更少的冗余代码并使其更易于管理。

我通过 ListFragment 中的条件语句调用不同的适配器类。我最初在 ListFragment 类中有适配器,这一切都按计划工作。现在要清理所有内容并从 ListFragment 中获取所有代码,我将适配器移出并移入它们自己的类中。既然这样做了,这些方法必须是静态的,所以我可以调用它们,但是这些新类现在包含很多:

无法从 ListFragment 类型对非静态方法 setListAdapter(ListAdapter) 进行静态引用

特别是 setListAdapter、setListAdapter、getFragmentManager 和 getFragmentManager 方法。我不想要大量的 ListView Fragment 类,并且由于会重用大量代码,因此只有一个 ListFragment 并使用条件来获得正确的适配器,因此会做得更多,但我不知道如何修复这些新类所以我可以使用它们。

抱歉,解释太长了。我将尝试仅发布相关代码以了解我要完成的工作并为您提供指导。

这可以按照我这样做的方式完成吗?我该如何纠正?

如果有更好的方法,请在我的适配器类中发布一些您的解释或代码中需要更改的代码。

在我的片段的 onActivityCreated 中:

. . .

    // Get the string to query from last Fragment and pass it to this
    // Fragment
    Bundle args = this.getArguments();

    boolean rawRes = args.getBoolean(KEY_IS_RAW_RES);
    String url = args.getString(KEY_URL);
    int fileName = args.getInt(KEY_RES_FILE);

    this.getJsonFile(url, rawRes, fileName);

}

public void getJsonFile(String url, boolean rawRes, int fileName) {

    if (rawRes == true) {
        getFromRawRes(fileName);
    } else {
        getFromURL(url);
    }
}

public void getFromRawRes(int fileName) {
        InputStream file = getResources().openRawResource(fileName);
        JSONParser jParser = new JSONParser();
        JSONArray json = jParser.getJSONFromRes(file);
        ListAdapter_SevenItem.callback(json, context);//<--THIS IS A CALL TO THE ADAPTER!!
    }

适配器之一:

public class ListAdapter_SevenItem extends ListViewFragment {

. . .

public static void callback(JSONArray json, Context c) {
    if (json != null) {
    // Hashmap for ListView
    . . .
    // create the list item mapping
        String[] from = new String[]{TAG_LABEL, TAG_TITLE, TAG_DISCR, TAG_RES_FILE, TAG_IS_RAW_RES, TAG_CONT_ID};
        int[] to = new int[]{R.id.listLabel, R.id.listTitle, R.id.listDiscription, R.id.listResFile, R.id.listIsRawRes, R.id.listContID};

        // Updating parsed JSON data into ListView
        SimpleAdapter adapter = new SimpleAdapter(c, mList, R.layout.list_item, from, to);
        setListAdapter(adapter);

        // selecting single ListView item
        final ListView lv = setListAdapter();

        // Launching new screen on Selecting Single ListItem
        lv.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
                MainActivity.mLayout.toggleSidebar();
                setHasOptionsMenu(true);

                FragmentManager fm = getFragmentManager();
                final FragmentTransaction lcFT = fm.beginTransaction();
                lcFT.setCustomAnimations(R.anim.slide_in, R.anim.hyperspace_out, R.anim.hyperspace_in, R.anim.slide_out);

                final Bundle args = new Bundle();

                String resFile = ((TextView) view.findViewById(R.id.listResFile)).getText().toString();
                int passResFile = getFragmentManager().getIdentifier(resFile, "raw", "com.andaero.app");
                args.putInt("KEY_RES_FILE", passResFile);

                boolean isRawRes = true;
                args.putBoolean("KEY_IS_RAW_RES", isRawRes);

                // Delayed to improve animations
                final Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    public void run() {
                        ListViewFragment lvf = new ListViewFragment();
                        lcFT.replace(R.id.listContainer, lvf).commit();
                        lvf.setArguments(args);
                    }
                }, 300);
            }
        });
    }
}

}

4

2 回答 2

0

你把事情复杂化了。

不应该有像您使用的那样的静态方法/调用。应该很简单。在列表片段中onActivityCreated(Bundle savedInstanceState),您创建列表适配器的一个实例,并使用setListAdapter().

检查片段教程中的 TitlesFragment 示例。

于 2012-06-13T19:22:23.870 回答
0

可以在应用程序中重用的 ListView 片段类。

我使用 jgilfelt 的通用JasonArrayAdapter类,可以在 GitHub 上下载。下面的类可以在整个应用程序中反复使用,因此它是唯一需要的 ListView 类——这意味着减少了冗余代码/类。特别是,如果您有需要不同属性和/或布局的列表视图。

如果您从另一个 Fragment 加载此 ListViewFragment:

String uri = "http://www.xxxx/myjsonfile.json";//EXAMPLE IF FROM A URL
String uri = "json/myjsonfile.json";//EXAMPLE GETTING FROM YOUR ASSETS FOLDER
args.putString("KEY_URI", uri);

String adptrID = "#";//USED TO DETERMINE WHICH LAYOUT TO USE
args.putString("KEY_ADPTR_ID", adptrID);

ListViewFragment lvf = new ListViewFragment();
lcFT.replace(R.id.myContainer, lvf).commit();
lvf.setArguments(args);

如果您从自身加载此 ListViewFragment,只需在 JSON 文件中添加适当的项目并将它们放入您的 setArguments(args) Bundle。

如果您对方法有任何改进/等,请随时将其添加到您的评论/答案中。我是 Android 新手,边走边学... Thnx

ListViewFragment 类:

public class ListViewFragment extends ListFragment implements OnItemClickListener {
. . .
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        Bundle getArgs = this.getArguments();
        String URI = getArgs.getString(KEY_URI);
            . . .
        new GetJSONTask().execute(URI);
    }

    class GetJSONTask extends AsyncTask<String, Integer, String> {

        protected String doInBackground(String... arg0) {

            String uri = arg0[0];

            InputStream is = null;

            if (uri.contains("http") == true) {// Get JSON from URL
                try {
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(uri);
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();

                    BufferedReader rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    while ((line = rd.readLine()) != null) {
                        json += line;
                    }
                    rd.close();
                    return json;
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                  }
                } else {//Get JSON from Assets

                Writer writer = new StringWriter();
                char[] buffer = new char[1024];

                try {
                    InputStream jsonFile = getActivity().getAssets().open(uri);
                    Reader reader = new BufferedReader(new InputStreamReader(jsonFile, "UTF-8"));
                    int n;
                    while ((n = reader.read(buffer)) != -1) {
                        writer.write(buffer, 0, n);
                    }
                    jsonFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                json = writer.toString();
                // return JSON String
                return json;
            }
        }

        @Override
        protected void onPostExecute(String result) {
            try {
                showData(result);
            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(getActivity(), "something went wrong", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void showData(String json) throws JSONException {
        JSONObject o = new JSONObject(json);
        JSONArray data = o.getJSONArray("results");

        Bundle getArgs = this.getArguments();
        String adptrID = getArgs.getString(KEY_ADPTR_ID);

        if (adptrID == "3") {//Adapter for 3 items
            String[] from = new String[]{"label", "title", "description", "uri", "adapterID", "containerID"};
            int[] to = new int[]{R.id.listLabel, R.id.listTitle, R.id.listDiscription, R.id.listURI, R.id.listAdapterID, R.id.listContID};
            ListAdapter adapter = new JSONArrayAdapter(getActivity(), data, R.layout.list_item, from, to, null);
            getListView().setOnItemClickListener(this);
            getListView().setAdapter(adapter);
        }
        if (adptrID == "4") {//Adapter for 4 items - Get the idea?
        . . .
        } . . .//Additional Adapter can be added....
    }

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        final Bundle args = new Bundle();
        Bundle getArgs = this.getArguments();

        String uri = ((TextView) view.findViewById(R.id.listURI)).getText().toString();
        args.putString("KEY_URI", uri);

        String adptrID = ((TextView) view.findViewById(R.id.listAdapterID)).getText().toString();
        args.putString("KEY_ADPTR_ID", adptrID);

        String contID = ((TextView) view.findViewById(R.id.listContID)).getText().toString();
        args.putString("KEY_CONTAINER_ID", contID);

        //Conditional to determine witch container to load the ListViewFragment(this)
         if (containerID == "listContainer") {
         lcFT.replace(R.id.listContainer, lvf).commit();
         lvf.setArguments(args);
         }
         if (containerID == "someOtherContainer") {
         lcFT.replace(R.id.discriptionListContainer, lvf).commit();
         lvf.setArguments(args);
         }. . .
    }
于 2012-06-20T14:44:09.120 回答