Dynamic GridView items in Android

泄露秘密 提交于 2020-01-01 00:52:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!