Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

android - What does AdapterView<?> mean in the OnitemClick() Method? What is the use of other parameters in it?

gridview.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            Toast.makeText(HelloGridView.this, "" + position, Toast.LENGTH_SHORT).show();
        }
    });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The <?> indicates a Generic. Read more about them here.

Here is what the documentation says about the parameters:

onItemClick(AdapterView<?> parent, View view, int position, long id)

parent The AdapterView where the click happened.

view The view within the AdapterView that was clicked (this will be a view provided by the adapter)

position The position of the view in the adapter.

id The row id of the item that was clicked.

The AdapterView could be a ListView, GridView, Spinner, etc. The question mark inside the angle brackets indicates that it could be any of them. This is called generics in Java. You can use parent in code to do something to the whole view. For example, if you were using a ListView you could hide the whole ListView by the following line of code:

parent.setVisibility(View.GONE);

The View refers to a specific item within the AdapterView. In a ListView it is the row. Thus, you can get a reference to a TextView within a row by saying something like this:

TextView myTextView = (TextView) view.findViewById(R.id.textView1);
String text = myTextView.getText().toString();

The position is the position of the view in the parent. For a ListView, it is the row number. The top row is position 0, the second row is position 1, the third row is position 2, etc. Note that if your ListView has a header view (like if you did ListView.addHeaderView(View)) then the header view would be position 0 and the actual rows would start their numbering at 1.

Sometimes id is the same as position and sometimes it is different. If you are using an ArrayAdapter or SimpleAdapter then they are the same (except in the case that there is a header view and then they are off by one). For a CursorAdapter (and consequently a SimpleCursorAdapter) the id returns the row id of the table, that is, _id.

Here are a few other good answers on this topic:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...