当我选择或点击GridView的数据时,我试图使用Toast查看GridView中的文本。我可以看到位置,但不知道该看什么文字。 这是一个代码。
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.Toast;
public class MainActivity extends Activity {
String [] data = {"a","b", "c","d","e","f", "g","h"};
GridView gdView;
ArrayAdapter<String> adapter;
String result;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new ArrayAdapter<String>(this, R.layout.item, R.id.tvText, data);
gdView = (GridView) findViewById(R.id.gdView);
gdView.setAdapter(adapter);
gdView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(getBaseContext(), position, Toast.LENGTH_SHORT).show();
}
});
}
}
有人可以建议我,我需要使用什么或在哪里寻找它? 谢谢
答案 0 :(得分:0)
将最后一个字符串转到
Toast.makeText(getBaseContext(), String.valueOf(position), Toast.LENGTH_SHORT).show();
答案 1 :(得分:0)
$instance->method1()/* returns $instance and can be used again*/->method2();
上方法int position
的参数onItemClick()
为您提供:
适配器中视图的位置。
见这里:https://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html#onItemClick(android.widget.AdapterView,android.view.View,int,long)
您可以使用此功能从AdapterView.OnItemClickListener
使用以下内容检索此视图的内容:
ArrayAdapter
见这里:https://developer.android.com/reference/android/widget/ArrayAdapter.html#getItem(int)
这将返回您adapter.getItem(position)
在给定位置的内容,在您的情况下为ArrayAdapter
,如果您愿意,可以将其存储在变量中,或直接传递到String
答案 2 :(得分:0)
您可以如下:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// First Approach
// Although your Adapter is fed with <String> data, type check is safe
if (parent.getItemAtPosition(position) instanceof String) {
String s1 = (String) parent.getItemAtPosition(position);
}
// 2nd Approach
TextView myView = (TextView) view.findViewById(R.id.tvText);
if(myView!=null && myView.getText()!=null) {
String s2 = myView.getText().toString();
}
// 3rd Approach
// As mentioned in @ci_ answer in this post
}
希望这有帮助!