-1

当用户点击一个按钮时,一个新的字符串被添加到列表视图中,但是当我点击它时什么都没有出现。我该怎么做呢?

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);
    }
}

片段匹配.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>
4

1 回答 1

1

listAdapter.add(...)相反(然后不需要打电话notifyDataSetChanged())。

例如,如果您使用过滤器,ArrayAdapter 可以在内部使用另一个列表,除了不好的做法,因为 ArrayAdapter 可以只对构造函数中传递的该列表进行防御性副本(尽管它没有)。它使用内部锁来保护该列表。所以真的不应该在外面修改它。

于 2012-12-22T21:30:28.880 回答