When the user clicks a button, a new string is added to the list view, but nothing is appearing when i click it. How exactly would I do that?
MatchesList.java
The class that adds the strings to the list view
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>
listAdapter.add(...)instead (and no need to callnotifyDataSetChanged()then).ArrayAdapter can use another list internally if you are using filter for example, besides not good practice as the ArrayAdapter could just do a defensive copy of that list passed in the constructor (it doesn’t though). It is using an internal lock to protect that list though. So really isn’t supposed to modify it outside.