<TableRow
android:id="@+id/Row3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center">
<TextView
android:id="@+id/cell31"
android:layout_height="fill_parent"
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="center"
android:textSize="50sp"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceLarge"
android:background="@drawable/back"
android:onClick="cellClick"
android:clickable="true"/>
<TextView
android:id="@+id/cell32"
android:layout_height="fill_parent"
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="center"
android:textSize="50sp"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceLarge"
android:background="@drawable/back"
android:onClick="cellClick"
android:clickable="true"/>
.... this is 5x5 row column table. with 25 cells in it.
我的.xml文件如下所示。我在LinearLayout中有很多行包含TableLayouts,其中包含TextViews作为单元格。我和他们一起做了一个基本的游戏。 我试图将.xml中的每个单元格分配给.java文件中的TextView数组。但我无法弄清楚如何制作它。我需要根据我制作的一些算法改变每个单元格的颜色,这样我才能访问单元格。
private TextView colorBoard[][];
this is my .java array.
我可以检查是否点击了
public void cellClick(View v) {
TextView cell = (TextView) findViewById(v.getId());
switch (cell.getId()) {
case R.id.cell11:
xloc = 0;
break;
case R.id.cell12:
xloc = 1;
break ;
...rest of cells
但是我只能分配一下当时点击的单元格。在我的游戏中,单元格的颜色会有所不同。不是你刚刚点击的那个。假设您单击1x3并且4x4可能会更改颜色。
我是Android的新手,这是我的第一个项目,如果我遗漏了一些基本内容,那就很抱歉。
答案 0 :(得分:1)
我认为你应该使用ListView而不是TextView。在ListView中,您可以使用数组来分配那些您想要使用它们的东西。
您可以像这样创建布局文件:
<ListView>
android:weight="match_parent"
android:height="match_parent"
android:id="+id/lst_view"
</ListView>
您的Java代码如下所示
String[] array={"stack","queue","arraylist"};
ListView lst;
//In onCreate function
lst=(ListView)findViewById(R.id.lst_view);
ArrayAdapter<String> adpt=new ArrayAdapter<String>(this,R.layout.what_ever_your_xml,array);
lst.setAdapter(adpt);
//function of listview
//arrayadapter is used for converting string type array into listview
lst.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String s;
s=((TextView)view).getText().toString();
Toast.makeText(getApplicationContext(), s,Toast.LENGTH_LONG).show();
}
});
答案 1 :(得分:0)
如果要为TextView Array分配值。 然后在setContentView
之后的oncreate方法中这样做 colorBoard[0][0] = (TextView) findViewById(R.id.cell11);
colorBoard[0][1] = (TextView) findViewById(R.id.cell12);
您可以使用findviewbyId将TextView从xml获取到Java。
假设您在点击cell11时想要访问cell44,那么您可以执行类似这样的操作。
public void cellClick(View v) {
TextView cell = (TextView) findViewById(v.getId());
switch (cell.getId()) {
case R.id.cell11:
xloc = 0;
colorBoard[0][0].setBackground()//As you wish
break;
case R.id.cell12:
xloc = 1;
break ;
...rest of cells
一旦您有权访问cell44,您可以为其设置背景颜色或任何其他属性。