0

我試圖將一些自定義列表適配器放到它們自己的類中,以使我的應用程序擁有更少的冗餘代碼並使其更易於管理。Android ListAdapter如何更正:無法對靜態方法進行靜態引用

我通過ListFragment中的條件語句調用不同的適配器類。我原本在ListFragment類中有適配器,並且這一切都按照計劃進行。現在要清理所有內容並將所有代碼從ListFragment中移出,我將適配器移出並放入他們自己的類中。因爲這是完成的,這些方法必須是靜態的,所以我可以叫上他們,但這些新的類現在containa很多:

不能使靜態參考來自非靜態方法 setListAdapter(ListAdapter) type ListFragment

具體來說就是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); 
      } 
     }); 
    } 
} 

}

回答

0

一個ListView片段類,可以重用一個應用程序。

我使用jgilfelt的通用JasonArrayAdapter類,可以在GitHub上下載。下面的類可以反覆使用,因此它只需要一個ListView類 - 這意味着減少冗餘代碼/類。特別是,如果你有列表視圖需要不同的屬性和/或佈局。

如果您加載此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(參數)軟件包。

如果您對這些方法有任何改進,請隨時將它添加到您的評論/答案中。我是新來的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); 
     }. . . 
    } 
0

你過於複雜的事情。

不應該有像你使用的靜態方法/調用。它應該非常簡單。在列表片段的onActivityCreated(Bundle savedInstanceState)中,您將創建列表適配器的實例,並使用setListAdapter()將其設置爲適配器。

檢查tutorial on fragments中的TitlesFragment樣本。

+0

日Thnx的評論。有幾個數據源(大多數是JSON)從(本地,遠程等)填充,需要解析器和大量的捆綁參數傳遞。如果我可以使用本教程中實現的基本方法,那麼我會從字面上獲得數百個ListView片段,其中一半的代碼將在其中重複使用。它基本上是什麼:加載片段 - >確定數據來自哪個src - >確定需要什麼解析器 - >解析它 - >發送要映射到視圖 - >顯示列表視圖。我是新來的機器人,所以幫助表示讚賞! – CelticParser

+0

另一點:'ListAdapter_SevenItem擴展ListViewFragment'看起來非常可疑。爲什麼'ListAdapter'擴展'Fragment'?這是兩個完全不同的概念。 –

相關問題