我必须为我的项目在android中做一个备忘录卡游戏。就目前而言,我正处于尝试弄清楚我的应用程序的基本形状的阶段。
I ve read some tutorials, but i can;t figure out how to modify a lot of dynamically created buttons (ie. in for loop), from xml, or even from the code. To make my question clear here s the code i made
package piotrek.test1;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.*;
import android.widget.*;
import java.util.ArrayList;
import java.util.*;
public class test1 extends Activity implements View.OnClickListener {
private ArrayList<Integer> listaKart = new ArrayList<Integer>();
private int rozmiar = 0;
private int licznik = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TworzKarty();
//tu tworzymy definicje nowego wygladu (layout) czyli w formie tabeli
TableLayout layout = new TableLayout (this);
layout.setLayoutParams( new TableLayout.LayoutParams(4,5) );
//ustawienie odstepow do scian
layout.setPadding(10,10,10,10);
//petle populujace miejsca w tabeli przyciskami
for (int f=0; f<=5; f++) {
TableRow tr = new TableRow(this);
for (int c=0; c<=4; c++) {
ToggleButton b = new ToggleButton (this);
//b.setText(""+f+c);
b.setText(Integer.toString(listaKart.get(licznik)));
b.setTextSize(10.0f);
b.setTextColor(Color.rgb( 100, 200, 200));
b.setOnClickListener(this);
tr.addView(b, 60,60);
licznik++;
} // for
layout.addView(tr);
} // for
super.setContentView(layout);
} // ()
public void TworzKarty(){
for (int i=0;i<=14;i++){
this.listaKart.add(i);
this.listaKart.add(i);
}
//pomieszanie kolejnosci numerków
Collections.shuffle(listaKart);
rozmiar=listaKart.size();
}
public void onClick(View view) {
//((Button) view).setText("*");
//((Button) view).setEnabled(false);
if (((ToggleButton) view).isChecked()) {
Toast.makeText(test1.this, Integer.toString(rozmiar), Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(test1.this, "Not checked", Toast.LENGTH_SHORT).show();
}
}
} // class
What happens when i run the app is, that i have 30 togglebuttons on the screen, each of them has a number form 0 to 14 (15 pairs). That s what i wanted to have, but when i press any of them buttons besides showing the toast button text changes form what i want it to be to ON and then after another press to OFF. I can t figure out how to control this behaviour - i would really appreciate some tips on how to achieve this strictly in code or using xml. Another case is how to use xml to define such layout and randomness of the text set on buttons.