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

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>
4

1 に答える 1

1

listAdapter.add(...)代わりに (その場合は呼び出す必要はありませんnotifyDataSetChanged())。

たとえば、フィルターを使用している場合、ArrayAdapter は内部で別のリストを使用できますが、ArrayAdapter はコンストラクターで渡されたそのリストの防御的なコピーを実行できるため、お勧めできません (ただし、そうではありません)。ただし、そのリストを保護するために内部ロックを使用しています。したがって、実際には外部で変更することは想定されていません。

于 2012-12-22T21:30:28.880 に答える