2011-12-14 3 views
2

목록보기에 목록 항목을 동적으로 삽입하려고합니다. 목록보기가 생성되어 화면에 표시되면 이제 서버 또는 일부 항목에서 하나의 항목을 얻었고 이제는이 항목을 동일한 목록보기에 내가 추가 한 항목으로 추가하려고합니다. 그렇게하는 방법 ?? 표시된 목록보기에서 항목을 동적으로 삽입 할 수있는 방법이 있습니까? 그리고 목록 항목의 상태를 변경할 수있는 방법이 있습니까? 즉, 표시되는 동안 상호 작용할 수 있습니까? 귀하의 회신을 부탁드립니다. 사전에 Thnx!ListView 활동, 목록 항목의 동적 삽입

답변

5

당신의 Adapter에서 사용 후가 될 것 정기적 ArrayAdapter와 함께 Adapter

notifiyDataSetChanged()를 호출되고있는 데이터 구조합니다 (List를 의미)로 당신이 원하는대로 추가 뭔가 같은 :

MyAdapter adapter = new MyAdapter(this, R.layout.row, myList); 
listView.setAdapter(adapter); 
... 
//make a bunch of changes to data 
list.add(foo); 
listView.getAdapter().notifyDataSetChanged(); 

더 복잡한 예제를 BaseAdapter과 함께 제공 할 수 있습니다. 이 질문은 매우 일반적인 것 같다 때문에

편집은 좀 샘플을 만들었습니다.

필자가 만든 샘플에서 모든 것을 한 곳에서 수행하기가 더 쉬워지기 위해 모든 것을 한 클래스에서 수행했습니다.

결국 모델 뷰 컨트롤러 유형의 상황입니다. 당신도 여기에서 그것을 복제하여 실제 프로젝트를 실행할 수 있습니다 https://github.com/levinotik/Android-Frequently-Asked-Questions

그것의 본질은 이것이다 : 당신이 여기 개념을 파악 경우

/** 
* This Activity answers the frequently asked question 
* of how to change items on the fly in a ListView. 
* 
* In my own project, some of the elements (inner classes, etc) 
* might be extracted into separate classes, but for clarity 
* purposes, I'm doing everything inline. 
* 
* The example here is very, very basic. But if you understand 
* the concept, it can scale to anything. You have complex 
* views bound to complex data wit complex conditions. 
* You could model a facebook user and update the ListView 
* based on changes to that user's data that's represented in 
* your model. 
*/ 
public class DynamicListViewActivity extends Activity { 

    MyCustomAdapter mAdapter; 

    @Override 
    public void onCreate(Bundle state) { 
     super.onCreate(state); 
     ListView listView = new ListView(this); 
     setContentView(listView); 

     /** 
     * Obviously, this will typically some from somewhere else, 
     * as opposed to be creating manually, one by one. 
     */ 

     ArrayList<MyObject> myListOfObjects = new ArrayList<MyObject>(); 

     MyObject object1 = new MyObject("I love Android", "ListViews are cool"); 
     myListOfObjects.add(object1); 
     MyObject object2 = new MyObject("Broccoli is healthy", "Pizza tastes good"); 
     myListOfObjects.add(object2); 
     MyObject object3 = new MyObject("bla bla bla", "random string"); 
     myListOfObjects.add(object3); 

     //Instantiate your custom adapter and hand it your listOfObjects 
     mAdapter = new MyCustomAdapter(this, myListOfObjects); 
     listView.setAdapter(mAdapter); 

     /** 
     * Now you are free to do whatever the hell you want to your ListView. 
     * You can add to the List, change an object in it, whatever. 
     * Just let your Adapter know that that the data has changed so it 
     * can refresh itself and the Views in the ListView. 
     */ 

     /**Here's an example. Set object2's condition to true. 
     If everyting worked right, then the background color 
     of that row will change to blue 
     Obviously you would do this based on some later event. 
     */ 
     object2.setSomeCondition(true); 
     mAdapter.notifyDataSetChanged(); 



    } 


    /** 
    * 
    * An Adapter is bridge between your data 
    * and the views that make up the ListView. 
    * You provide some data and the adapter 
    * helps to place them into the rows 
    * of the ListView. 
    * 
    * Subclassing BaseAdapter gives you the most 
    * flexibility. You'll have to override some 
    * methods to get it working. 
    */ 
    class MyCustomAdapter extends BaseAdapter { 

     private List<MyObject> mObjects; 
     private Context mContext; 

     /** 
     * Create a constructor that takes a List 
     * of some Objects to use as the Adapter's 
     * data 
     */ 
     public MyCustomAdapter(Context context, List<MyObject> objects) { 
      mObjects = objects; 
      mContext = context; 
     } 

     /** 
     * Tell the Adapter how many items are in your data. 
     * Here, we can just return the size of mObjects! 
     */ 
     @Override 
     public int getCount() { 
      return mObjects.size(); 
     } 

     /** 
     * Tell your the Adapter how to get an 
     * item as the specified position in the list. 
     */ 
     @Override 
     public Object getItem(int position) { 
      return mObjects.get(position); 
     } 

     /** 
     * If you want the id of the item 
     * to be something else, do something fancy here. 
     * Rarely any need for that. 
     */ 
     @Override 
     public long getItemId(int position) { 
      return position; 
     } 

     /** 
     * Here's where the real work takes place. 
     * Here you tell the Adapter what View to show 
     * for the rows in the ListView. 
     * 
     * ListViews try to recycle views, so the "convertView" 
     * is provided for you to reuse, but you need to check if 
     * it's null before trying to reuse it. 
     * @param position 
     * @param convertView 
     * @param parent 
     * @return 
     */ 
     @Override 
     public View getView(int position, View convertView, ViewGroup parent) { 
      MyView view; 
      if(convertView == null){ 
       view = new MyView(mContext); 
      } else { 
       view = (MyView) convertView; 
      } 
      /**Here's where we utilize the method we exposed 
      in order to change the view based on the data 
      So right before you return the View for the ListView 
      to use, you just call that method. 
      */ 
      view.configure(mObjects.get(position)); 

      return view; 
     } 
    } 


    /** 
    * Very simple layout to use in the ListView. 
    * Just shows some text in the center of the View 
    */ 
    public class MyView extends RelativeLayout { 

     private TextView someText; 

     public MyView(Context context) { 
      super(context); 

      LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
      params.addRule(CENTER_IN_PARENT); 
      someText = new TextView(context); 
      someText.setTextSize(20); 
      someText.setTextColor(Color.BLACK); 
      someText.setLayoutParams(params); 
      addView(someText); 
     } 

     /** 
     * Remember, your View is an regular object like any other. 
     * You can add whatever methods you want and expose it to the world! 
     * We have the method take a "MyObject" and do things to the View 
     * based on it. 
     */ 

     public void configure(MyObject object) { 

      someText.setText(object.bar); 
      //Check if the condition is true, if it is, set background of view to Blue. 
      if(object.isSomeCondition()) { 
       this.setBackgroundColor(Color.BLUE); 
      } else { //You probably need this else, because when views are recycled, it may just use Blue even when the condition isn't true. 
       this.setBackgroundColor(Color.WHITE); 
      } 
     } 
    } 

    /** 
    * This can be anything you want. Usually, 
    * it's some object that makes sense according 
    * to your business logic/domain. 
    * 
    * I'm purposely keeping this class as simple 
    * as possible to demonstrate the point. 
    */ 
    class MyObject { 
     private String foo; 
     private String bar; 
     private boolean someCondition; 


     public boolean isSomeCondition() { 
      return someCondition; 
     } 


     MyObject(String foo, String bar) { 
      this.foo = foo; 
      this.bar = bar; 
     } 

     public void setSomeCondition(boolean b) { 
      someCondition = b; 
     } 
    } 

} 

, 당신이 적용 할 수 있어야한다 (웃기려는 의도 없음) ArrayAdapters이, 필요할 때마다 등

+0

샘플 코드로 정교하게 만들 수 있습니까 ?? 나에게 더 도움이 될 것이다. –

+0

괜찮습니다. 일부 목록보기 항목 (예 : 대화 상대 목록)이 있다고 가정하면 현재 온라인 또는 오프라인 상태가 서버 쪽에서 또는 일부에서 온 것으로 가정하여 특정 목록 항목의 텍스트 색을 변경하려고합니다. 내가 어떻게 할 수 있을까 ?? –

+0

@Arfin, 참으로 BaseAdapter를 사용하고 getView를 오버라이드하고 뷰를 반환하기 직전에 상태를 확인하고 필요에 따라 뷰를 변경하십시오. – LuxuryMode

0

예, 어댑터를 사용하여리스트 뷰에 기입을, 업데이트 항목 등 새 항목을 추가

당신은 인터넷을 통해 데이터를 당겨하는 경우, 당신이 할 수있는 일반 ArrayAdapter (평소 사용)으로 시작하십시오. 레이아웃을 구현하기 위해 getView() 메서드를 서브 클래 싱하고 오버라이드 한 다음 제공하는 목록에서 항목을 추가 및 제거합니다. 항목을 목록에 추가하면 아래로 스크롤 할 때 (또는 바로 아래에있는 경우) 목록 끝에 항목이 나타납니다. 항목을 수정하면 목록이 화면에서 즉시 업데이트됩니다.

모델 개체에 setter를 사용하는 경우 어댑터는 이에 대해 알지 못하지만 notifyDataSetChanged()으로 전화 할 수 있습니다. 또한 화면에 깜박임을 발생시키지 않고 목록을 여러 번 변경하려는 경우에 대비하여 setNotifyOnChange() 메소드를 살펴 보는 것이 좋습니다.

+0

can plz elaborate 샘플 코드를 사용하면 더 도움이 될 것입니다. –

+0

@LuxuryMode는 이미 자세한 코드 예제를 생성했습니다. – zostay