2012-12-22 60 views
-1

當用戶點擊一個按鈕時,一個新的字符串被添加到列表視圖中,但是當我點擊它時沒有任何東西出現。我究竟該怎麼做?Listview不從片段更新

MatchesList.java ,增加的字符串列表視圖

import java.util.ArrayList; 

import com.actionbarsherlock.app.SherlockListActivity; 

import android.app.ListActivity; 
import android.os.Bundle; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.ArrayAdapter; 
import android.widget.Button; 

public class MatchesList extends SherlockListActivity{ 
    ArrayList<String> listItems = new ArrayList<String>(); 
    ArrayAdapter<String> adapter; 

    int matchNum=0; 
    Button addMatch; 

    @Override 
    public void onCreate(Bundle icicle){ 
     super.onCreate(icicle); 
     setContentView(R.layout.fragment_matches); 
     adapter= new ArrayAdapter<String>(this, 
       android.R.layout.simple_list_item_1, 
       listItems); 

     setListAdapter(adapter); 

     addMatch = (Button) findViewById(R.id.addMatchBtn); 
     addMatch.setOnClickListener(new OnClickListener(){ 
      public void onClick(View v){ 
      addMatch(v); 
      } 
     }); 


    } 

    public void addMatch(View view){ 
     matchNum += 1; 
     listItems.add("Match " + matchNum); 
     adapter.notifyDataSetChanged(); 
    } 

} 

MatchesFragment.java

import com.actionbarsherlock.app.SherlockFragment; 

import android.os.Bundle; 
import android.view.*; 

public class MatchesFragment extends SherlockFragment{ 

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

fragment_matches.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context=".MatchesFragment" > 

    <Button 
     android:id="@+id/addMatchBtn" 
     android:layout_width="50dp" 
     android:layout_height="40dp" 
     android:text="Add a Match" 

    /> 


    <ListView 
     android:id="@android:id/list" 
     android:layout_width="match_parent" 
     android:layout_height="fill_parent"></ListView> 

</LinearLayout> 
+1

是否調用adapter.add()而不是listItems.add()使新字符串出現在列表中? –

+0

我改變了它,但它還沒有出現 – rasen58

回答

1

listAdapter.add(...)而不是類(沒有那麼需要撥打notifyDataSetChanged())。

如果您使用的是過濾器,ArrayAdapter可以在內部使用另一個列表,除非不是好的做法,因爲ArrayAdapter可以只是在構造函數中傳遞該列表的防禦副本(它不會)。它使用內部鎖來保護該列表。所以真的不應該在外面修改它。

+0

什麼是listAdapter? – rasen58

+0

由於某種原因,它甚至沒有進入MatchesList.java – rasen58