问题
Hey i'm trying to build an app in which the user can input some numbers and these numbers will be shown in a gridview with custom grid view items. If i use the common gridview items of android it works. But if i use my own layout it doesnt work. Only the first element in the array will be shown. Does anybody have a clou why this doesn't work?
public class GridViewAppActivity extends Activity {
private ArrayList<String> items;
private GridViewAdapter adapter;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
items = new ArrayList<String>();
adapter = new GridViewAdapter(this);
GridView gridView = (GridView) findViewById(R.id.gridView);
gridView.setAdapter(adapter);
final Button addButton = (Button) findViewById(R.id.add_button);
final EditText itemEditText = (EditText) findViewById(R.id.number_field);
// Click listener for Button
addButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
items.add(itemEditText.getText().toString());
itemEditText.setText("");
adapter.notifyDataSetChanged();
}
});
}
public class GridViewAdapter extends BaseAdapter {
private Context mContext;
public GridViewAdapter(Context c) {
mContext = c;
}
public int getCount() {
return items.size();
}
public Object getItem(int position) {
return items.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v;
if(convertView==null){
LayoutInflater li = getLayoutInflater();
v = li.inflate(R.layout.grid_item, null);
TextView tv = (TextView)v.findViewById(R.id.grid_item_text);
tv.setText(items.get(position));
} else {
v = convertView;
}
return v;
}
}
}
回答1:
Try this,
public View getView(int position, View convertView, ViewGroup parent) {
View v;
if(convertView == null) {
LayoutInflater li = getLayoutInflater();
v = li.inflate(R.layout.grid_item, null);
} else {
v = convertView;
}
TextView tv = (TextView)v.findViewById(R.id.grid_item_text);
tv.setText(items.get(position));
return v;
}
来源:https://stackoverflow.com/questions/8021528/dynamic-gridview-items-in-android