我的应用程序将有 5-15 个按钮,具体取决于后端可用的内容。如何定义正确的 GridView 布局文件以包含一组按钮,每个按钮都有不同的文本和其他属性?每个按钮本质上都会将一个商品添加到购物车,因此除了添加到购物车的商品之外,onClick 代码将是相同的。
如何定义一个数组,以便添加可变数量的按钮,但仍通过唯一 ID 引用每个按钮?我见过的例子数组.xml http://developer.android.com/guide/samples/ApiDemos/res/values/arrays.html,但他们创建了一个预先设置的字符串数组。我需要一种方法来创建对象,而不需要在布局或数组 xml 文件中定义文本。
更新 - 添加了有关添加到 GridView 的信息
我想将其添加到 GridView,因此调用 [addView 方法](http://developer.android.com/reference/android/widget/AdapterView.html#addView(android.view.View,%20int) http://developer.android.com/reference/android/widget/AdapterView.html#addView(android.view.View,%20int)导致 UnsupportedOperationException。我可以执行以下操作:
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 中完成吗?
在下面的代码中,您应该更改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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)