开发者

Identical views in ViewFlipper with diffrent click listeners

开发者 https://www.devze.com 2023-03-10 19:20 出处:网络
I have got a ViewFlipper that gets populated with multiple views, that are actually the same view over and over again. Everything works fine but settings an onClickListener to a button works not like

I have got a ViewFlipper that gets populated with multiple views, that are actually the same view over and over again. Everything works fine but settings an onClickListener to a button works not like expected:

flipStack = (ViewFlipper) findViewById(R.id.clubViewFlipper);

for(int i=0; i<= clubDataSet.size()-1; i++) {
clubData = clubDataSet.get(i);

    LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = vi.inflate(R.layout.detail_overlay, (ViewGroup)findViewById(R.id.clubDetailScrollView), false);

    Button websiteButton = (Button) view.findViewById(R.id.clubDetailWebsit开发者_如何学GoeButton);
    websiteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(webIntent);
        }
    });

    flipStack.addView(view);
}

Every single websiteButton of the ViewFlipper's views is set to the same URL now. Is there a way to change that or is my approach with a ViewFlipper wrong?

Thanks!

brejoc


You can use the tag:

flipStack = (ViewFlipper) findViewById(R.id.clubViewFlipper);

for(int i=0; i<= clubDataSet.size()-1; i++) {
clubData = clubDataSet.get(i);

    LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = vi.inflate(R.layout.detail_overlay, (ViewGroup)findViewById(R.id.clubDetailScrollView), false);

    Button websiteButton = (Button) view.findViewById(R.id.clubDetailWebsiteButton);

    // set the button's tag to be the url of the club
    websiteButton.setTag(clubData.getUrl());
    websiteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // fetch the URL from the tag.
            Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(v.getTag().toString()));
            startActivity(webIntent);
        }
    });

    flipStack.addView(view);
}


It looks okay, except you never change the URL. If you want different url's for each view, you need to change it somewhere within the loop. You could set them up in a String[] corresponding to your views, and just use urls[i] in that case. That's one way, anyway.

0

精彩评论

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