在Android应用程序的GridView中添加按钮数组
我有一个应用程序将有5-15个按钮,具体取决于后端可用的按钮。如何定义合适的GridView布局文件以包含一组按钮,每个按钮都有不同的文本和其他属性?每个按钮基本上都会将商品添加到购物车,因此除了添加到购物车的商品之外,onClick代码将保持不变。在Android应用程序的GridView中添加按钮数组
我该如何定义一个数组,以便可以添加可变数量的按钮,但是仍然通过唯一ID引用每个按钮?我看过arrays.xml的例子,但他们创建了一组预先设置的字符串。我需要一种方法来创建一个对象,而不是在布局或数组xml文件中定义文本。 。
更新 - 增加了信息有关添加到GridView
我想要将它添加到GridView,所以调用一个UnsupportedOperationException的[addView方法(http://developer.android.com/reference/android/widget/AdapterView.html#addView(android.view.View,%20int)结果我可以做到以下几点:
ImageButton b2 = new ImageButton(getApplicationContext());
b2.setBackgroundResource(R.drawable.img_3);
android.widget.LinearLayout container = (android.widget.LinearLayout) findViewById(R.id.lay);
container.addView(b2);
但这并不布局的按钮在网格状,我想这可以在GridView进行
这里有一个很好的样本给你:?
https://developer.android.com/guide/topics/ui/layout/gridview.html
你应该只创建按钮,而不是imageviews在getView适配器方法。
如果您使用的是的GridView,或ListView控件(ETC),并产生意见通过适配器来填充他们getView(POS,convertView,ViewGroup中),你可能会遇到的困惑(我做一旦)。
如果您决定重新使用convertView参数,则必须重置其中的所有内容。这个框架传递给你的是一种古老的观点,目的是为了节省膨胀布局的成本。它几乎从来没有与位置有关,它在布局之前。
class GridAdapter extends BaseAdapter // assigned to your GridView
{
public View getView(int position, View convertView, ViewGroup arg2) {
View view;
if (convertView==null)
{
view = getLayoutInflater().inflate(R.layout.gd_grid_cell, null);
}
else
{
// reusing this view saves inflate cost
// but you really have to restore everything within it to the state you want
view = convertView;
}
return view;
}
// other methods omitted (e.g. getCount, etc)
}
我认为这代表对Android的东西,其中的概念是有点困难首先要把握一个,直到你意识到有内部可用一个显著优化(必须是不错的CPU一点点移动设备上)
在下面的代码中,您应该将for, 的上限更改为变量。
public class MainActivity
extends Activity
implements View.OnClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TableLayout layout = new TableLayout (this);
layout.setLayoutParams(new TableLayout.LayoutParams(4,5));
layout.setPadding(1,1,1,1);
for (int f=0; f<=13; f++) {
TableRow tr = new TableRow(this);
for (int c=0; c<=9; c++) {
Button b = new Button (this);
b.setText(""+f+c);
b.setTextSize(10.0f);
b.setTextColor(Color.rgb(100, 200, 200));
b.setOnClickListener(this);
tr.addView(b, 30,30);
} // for
layout.addView(tr);
} // for
super.setContentView(layout);
} //()
public void onClick(View view) {
((Button) view).setText("*");
((Button) view).setEnabled(false);
}
} // class
你能否更新此链接? – 2016-06-02 13:58:16