7

我正在开发适用于 Android 的填字游戏应用程序。

我有一个网格视图

public class MainActivity extends Activity {

private GridView gridView;
private Button button;
private ArrayAdapter<String> adapter;

static final String[] numbers = new String[] { "A", "B", "C", "D", "E",
        "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
        "S", "T", "U", "V", "W", "X", "Y", "Z", "A", "B", "C", "D", "E",
        "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
        "S", "T", "U", "V", "W", "X", "Y", "Z" };

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    gridView = (GridView) findViewById(R.id.gridView1);
    button = (Button) findViewById(R.id.buttonSubmit);

    adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, numbers);

    gridView.setAdapter(adapter);

    final StringBuilder sb = new StringBuilder();

    gridView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {
                TextView tv = (TextView) v;
                tv.setBackgroundColor(Color.GREEN);
                tv.setTag("1");
             Toast.makeText(getApplicationContext(),
             ((TextView) v).getText(), Toast.LENGTH_SHORT).show();            
        }
    });
}

public void onSubmitClick(View v){
    for(int i=0;i<adapter.getCount();i++){
         String s = adapter.getItem(i);
    }
}

xml文件:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

     <Button
        android:id="@+id/buttonSubmit"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" 
        android:text="Submit"
        android:onClick="onSubmitClick">
    </Button>

    <GridView
        android:id="@+id/gridView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@id/buttonSubmit"
        android:layout_alignParentTop="true"
        android:columnWidth="30dp"
        android:gravity="center"
        android:numColumns="auto_fit"
        android:stretchMode="columnWidth" >
    </GridView>

</RelativeLayout>

我想要的是遍历gridview并找到带有tag1的textviews ...但是adapter.getItem只返回字符串...有什么帮助吗?

4

1 回答 1

23

您可以使用以下命令遍历 a GridView(或任何其他ViewGroup)的所有子级getChildAt()

    for(int i = 0; i < myGridView.getChildCount(); i++) {
        TextView child = (TextView) mGridView.getChildAt(i);
        // do stuff with child view
    }

请注意,有时 aGridView的孩子是另一个ViewGroup,因此您可能需要遍历它的孩子等。


但是......更好的方法可能是保留一个单独List的“标记”元素。您可以在标记并遍历整个列表时简单地将它们添加到列表中。

于 2013-10-22T17:03:45.280 回答