开发者

ClassCastException Explanation

Good day, i was having a little trouble with the following code below and i got a solution from a ticked answer in this link. I would like to know why.

开发者_JAVA百科

Note: i had a similar type of layout as in the question, but with one TextView only.

solution link here

my code below:

    public void onItemClick(AdapterView<?> av, View v, int position, long id) {
        blueadapter.cancelDiscovery();

    String info = ((TextView) v).getText().toString(); //classcastException here
    String Bluetooth_address = info.substring(info.length()-17);
 }

so from his solution, if i change this to this

String info = ((TextView) v.findViewById(R.id.search_device_id)).getText().toString();

it solves my ClassCastException problem.

Now please can someone kindly explain to me or point me to the right direction, what he meant by in the answer "You receive the whole LinearLayout as the parameter v. You should try v.findViewById() and then use this textview." its nice it solves my problem, but i would like to understand why i had to do that?.. i have dealt with ListViews before, but i have not come across this, so its kind of strange for me. Thank you.


The View v that you get is the entire Layout for the object that has the TextView (and probably other views) inside it.

It is not the TextView itself, you have to find the TextView that is inside of it.


you can start by reading this : http://developer.android.com/reference/android/widget/LinearLayout.html

then take a look at the layout you declare for your item delegate.

Obviously you know that your textView is R.id.search_device_id, so you should understand that it is included in a layout, which is the whole cell, and which happens to be 'v'


It simply meant that the listitem is a LinearLayout and TextView is contained in it. The onItemClick takes the item root, not its contents directly. Something like this

<LinearLayout......>
    <TextView........../>
    ............
</LinearLayout>

So when you receive a click on the item, the items root, i.e. the LinearLayout is passed in the onItemClick.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜