java Gridview 中的新项目在运行时添加
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13451069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
New items in Gridview added at runtime
提问by user1835312
I have a problem with my shoping list application. I implemented a button adapter from this tutorialwhich I will use for adding products to list. Each buuton in my gridview will be a product and each product will have context menu where I can add it to list or delete the product.
我的购物清单应用程序有问题。我从本教程中实现了一个按钮适配器,我将使用它来将产品添加到列表中。我的 gridview 中的每个按钮都是一个产品,每个产品都有上下文菜单,我可以将其添加到列表或删除产品中。
Problem is that user should have ability to add new products or categories and I don't know how to add items to gridview at runtime. I thought that I could create some dynamic array like list in c++ but i'm new to android and java so I have no idea how to implement something like that.
问题是用户应该能够添加新产品或类别,而我不知道如何在运行时将项目添加到 gridview。我以为我可以在 C++ 中创建一些像 list 这样的动态数组,但我是 android 和 java 的新手,所以我不知道如何实现这样的东西。
I tried to implement stack but every time I try to push something app crashes. The same is with array list.
我尝试实现堆栈,但每次尝试推送应用程序时都会崩溃。数组列表也是如此。
ButtonAdapter :
按钮适配器:
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;
}
}
}
and in Grid Activity i have another arraylist
在网格活动中,我有另一个数组列表
public static ArrayList<String> arrayInGrid;
in onCreate:
在 onCreate 中:
gridView.setAdapter(new ButtonAdapter(this,arrayInGrid ));
but when i try to send new item to array program crashes.
但是当我尝试将新项目发送到数组时,程序崩溃了。
arrayInGrid.add("new");
In fact it crashes at
事实上,它崩溃于
arrayInAdapter.size();
in button adapter.
在按钮适配器中。
any ideas what is wrong?
任何想法有什么问题?
回答by Nirmal Raghavan
You can pass the values in your dynamic array to the BaseAdapter for that GridView. Here's a tutorial, Hope it will help you. http://www.mkyong.com/android/android-gridview-example/
您可以将动态数组中的值传递给该 GridView 的 BaseAdapter。给你一个教程,希望对你有帮助。 http://www.mkyong.com/android/android-gridview-example/