gpt4 book ai didi

android - 遍历gridview中的所有对象

转载 作者:行者123 更新时间:2023-11-29 14:19:52 24 4
gpt4 key购买 nike

我正在为 Android 开发 CrossWord 应用程序。

我有一个 GridView

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 的 TextView ......但是 adapter.getItem 只返回字符串......有什么帮助吗?

最佳答案

您可以使用 getChildAt() 遍历 GridView(或任何其他 ViewGroup)的所有子项:

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

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


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

关于android - 遍历gridview中的所有对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19523860/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com