2013-05-28 5 views
1

AsynTask를 사용하여 json의 listview에 데이터를 표시하고 있습니다.목록보기의 "구분 기호"

코드는 여기에 있습니다.

public class MenuTask extends AsyncTask<String, String, String> { 

    @Override 
    protected String doInBackground(String... arg0) { 
     // TODO Auto-generated method stub 
     List<NameValuePair> params = new ArrayList<NameValuePair>(); 
     // Getting JSON String from URL.............. 
     JSONObject jsonObject = jParser.makeHttpRequest(
       "http://smartaway.dk/json/submenu.php?resid=" + res_id, 
       "POST", params); 
     try { 
      bestdeal = jsonObject.getJSONArray(TAG_MENU); 

      ///LOOping through AllEvents........ 
      for (int i = 0; i < bestdeal.length(); i++) { 
       JSONObject e = bestdeal.getJSONObject(i); 
       String resname = e.getString(TAG_MENUNAME); 
       String city_state = e.getString(TAG_PRICE); 

       // Creating New HAsh Map......... 
       HashMap<String, String> map = new HashMap<String, String>(); 
       // adding each child node to HashMap key => value 
       // map.put(TAG_ID, id); 
       map.put(TAG_MENUNAME, resname); 
       map.put(TAG_PRICE, city_state); 
       /* 
       * map.put(TAG_STREET, street); map.put(TAG_COUSINE, 
       * cousine); map.put(TAG_RES_LOGO, reslogo); 
       */ 
       // adding HashList to ArrayList 
       bestdeal_list.add(map); 
      } 
      // } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 

    @SuppressWarnings("deprecation") 
    @Override 
    protected void onPostExecute(String result) { 

     super.onPostExecute(result); 

     /* 
     * if(bestdeal_list.isEmpty()){ AlertDialog alertDialog=new 
     * AlertDialog.Builder(getParent()).create(); 
     * alertDialog.setTitle("No Best Deal Found"); 
     * alertDialog.setButton("Ok", new DialogInterface.OnClickListener() 
     * { 
     * 
     * @Override public void onClick(DialogInterface dialog, int which) 
     * { 
     * 
     * 
     * } }); alertDialog.show(); } else{ 
     */ 
     /* 
     * if (bestdeal_list.isEmpty()) { 
     * Toast.makeText(getApplicationContext(), "Empty Menu", 
     * Toast.LENGTH_LONG).show(); } else{ 
     */ 
     runOnUiThread(new Runnable() { 
      public void run() { 
       /** 
       * Updating parsed JSON data into ListView 
       * */ 
       ListAdapter adapter = new SimpleAdapter(
         RestaurantDetails.this, bestdeal_list, 
         R.layout.menu_list, new String[] { TAG_MENUNAME, 
           TAG_PRICE }, new int[] { R.id.textView1, 
           R.id.textView3 }); 
       list.setAdapter(adapter); 

      } 
     }); 
    } 
    // } 
} 

모든 것이 잘 작동하지만 목록보기를 섹션으로 나누어 코드를 수정하고 싶습니다. 카테고리 1에서 처음 4 개의 목록 항목을 카테고리 2에서 다른 4 개의 목록 항목으로 원합니다. 확장 가능한 목록보기를 원하지 않습니다. 위에서 언급 한 코드를 수정하기 만하면됩니다. runOnUiThread(Runnable)를 통해 코드를 실행할 필요가 정말 없다, 그래서

+0

사용자 지정 어댑터를 구현하여이 작업을 수행 할 수 있습니다. http://stackoverflow.com/a/1606642/2410326 – ooops

+0

http://stackoverflow.com/questions/2394514/how-to-generate-a-listview-with-headers-above-some-sections –

답변

2
  1. onPostExecute는 주 ("UI") 스레드에서 호출되고있다.
  2. 같은 ListView에서 뷰의 두 가지 유형을 표시 할 경우에 당신은, 당신이 (당신의 예에서 List)를 설정하여 데이터를 정렬해야합니다 (Adapter.getViewTypeCount() 참조)를 공급하기 위해 Adapter을 수정해야합니다 그래서이 반영됩니다 귀하가 요청한 정렬 + 섹션을 선택하고 마지막으로 어댑터에서 처리해야합니다 (주어진 위치로 적절한 유형 /보기를 반환하십시오). Adapter.getItemViewType()Adapter.getView()도 참조하십시오.
+0

나는 것을 얻을 수 있습니다 게시물 위의 코드를 수정 한 후. –

+0

a. 'postExecute()'는 핵심 이슈와 관련이 없습니다. b. 추가 (TitleA), 추가 (DataA1), 추가 (DataA2) ..., 추가 (TitleB), 추가 (DataB1), 추가 (DataB2) ... -> 어댑터 데이터 세트의 내부 유형을 구분하는 여러 가지 방법 중 하나) – avimak

1

은에서 선택하기위한 몇 가지 옵션이 있습니다. 질문에 대한 의견 중 하나의 링크를 보거나 내가 잠시 후에 작성한 SectionedAdapter을 살펴보십시오. 당신이 기본적으로 수행 할 작업을

은 대부분 BaseAdapter에서 파생 된 사용자 정의 어댑터를 사용하는 것입니다. getViewTypeCount()을 무시하고 목록에있는 여러 종류의 목록 항목 수를 반환해야합니다. 귀하의 경우에는 정상적인 목록 항목과 카테고리가 있으므로 2입니다.

또한 getItemViewType(position)을 무시하고 지정된 위치의 항목이 일반 목록 항목 인 경우 0을 반환하거나 카테고리 인 경우 1을 반환해야합니다.

마지막으로 getView()을 재정의하고 getItemViewType()을 기반으로 적절한 유형 (카테고리 또는 일반 목록 항목)의 목록 항목을 반환해야합니다.

1

은 모두 britzl 및 avimak 좋은 답변을하는 듯했으나 일부 ​​사용 사례에 대한 간단하고 적합 할 수있는 다른 방법이있다.

먼저이 같은 목록 항목의 레이아웃을 지정 : 당신이 섹션 헤더 여부를 표시 할 경우

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" android:layout_height="wrap_content" > 

    <TextView 
     android:id="@+id/section_header" 
     android:layout_width="match_parent" android:layout_height="wrap_content" /> 

    <RelativeLayout 
     android:layout_below="@id/section_header" 
     android:layout_width="match_parent" android:layout_height="wrap_content"> 

     <!-- your layout here ... --> 

    </RelativeLayout> 

</RelativeLayout> 

그런 다음 어댑터를 결정합니다.

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    View view = super.getView(position, convertView, parent); 
    bindSectionHeader(position, view); 
    return view; 
} 

private void bindSectionHeader(int position, View view) { 
    TextView sectionView = (TextView) view.findViewById(R.id.section_header); 

    if (isBeginningOfSection(position)) { 
     sectionView.setText(getSectionTitle(position)); 
     sectionView.setVisibility(View.VISIBLE); 
    } else { 
     sectionView.setVisibility(View.GONE); 
    } 
} 

private boolean isBeginningOfSection(int position) { 
    // ... 
} 

private String getSectionTitle(int position) { 
    // ... 
} 

AlphabetIndexer

는 두 가지 방법을 구현하는 데 도움이 될 수 있습니다.