java - 运行时添加 Gridview 中的新项目

标签 java android gridview runtime adapter

我的购物 list 应用程序出现问题。我从这个 tutorial 实现了一个按钮适配器我将用它来将产品添加到列表中。我的 gridview 中的每个按钮都是一个产品,每个产品都有上下文菜单,我可以将其添加到列表中或删除产品。

问题是用户应该能够添加新产品或类别,但我不知道如何在运行时向 gridview 添加项目。我以为我可以在 c++ 中创建一些动态数组,例如列表,但我对 android 和 java 很陌生,所以我不知道如何实现类似的东西。

我尝试实现堆栈,但每次我尝试推送某些内容时应用程序都会崩溃。数组列表也是如此。

按钮适配器:

ButtonAdapter(Context c, ArrayList<String> array){
  mContext = c; 
  arrayInAdapter = array; } 


public int getCount() {  
    int a;
    a = arrayInAdapter.size();
 return a;  
}  

public View getView(int position, View convertView, ViewGroup parent) {  
 Button btn;  

 if (convertView == null) {  
  //if it's not recycled, initialize some attributes  
  btn = new Button(mContext);  
  btn.setLayoutParams(new GridView.LayoutParams(130, 130));  
  btn.setPadding(8, 8, 8, 8);  
 }  
 else {  
 btn = (Button) convertView;  
 }  
 btn.setText(arrayInAdapter.get(position));   
 btn.setTextColor(Color.RED);  
 btn.setBackgroundResource(R.drawable.sample_0);  
 btn.setId(position); 
 btn.setOnClickListener(new MyOnClickListener(position));

 return btn;  
}  

}

在网格 Activity 中我有另一个数组列表

public static ArrayList<String> arrayInGrid;

在 onCreate 中:

gridView.setAdapter(new ButtonAdapter(this,arrayInGrid ));  

但是当我尝试将新项目发送到数组时程序崩溃。

arrayInGrid.add("new");

事实上它崩溃于

arrayInAdapter.size();  

在按钮适配器中。

有什么问题吗?

最佳答案

您可以将动态数组中的值传递给该 GridView 的 BaseAdapter。 这是一个教程,希望对您有所帮助。 http://www.mkyong.com/android/android-gridview-example/

关于java - 运行时添加 Gridview 中的新项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13451069/

相关文章:

java - 调用 socket.bind() 时应用程序关闭 - Android 上的 JeroMQ

Android Python 缺少基本模块

android - Google Analytics V2 - IllegalStateException - 我可以在 onCreate() 而不是 onStart() 中初始化吗

android - 从Gridview动态切换到Listview

以特定图像打开的 Android 画廊

java - CLIPS 查找所有事实返回值

java - Clojure data.xml 错误

android - 错误 : onNewIntent not called for singleTop activity with Intent. FLAG_ACTIVITY_NEW_TASK

javascript - SproutCore 的按钮格式错误

Java - 是否可以将客户端发送到另一台服务器?