Unable to get the card index

2019-09-10 06:43发布

问题:

I am trying to get the index of the card which is active on the screen with this code.

import java.util.ArrayList;
import java.util.Arrays;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.glass.app.Card;
import com.google.android.glass.touchpad.Gesture;
import com.google.android.glass.touchpad.GestureDetector;
import com.google.android.glass.widget.CardScrollAdapter;
import com.google.android.glass.widget.CardScrollView;
import com.google.api.services.mirror.model.TimelineItem;

public class MainActivity extends Activity {
    private GestureDetector mGestureDetector;
    String identifysource;
    int cardindex;
    private static ArrayList<Card> sourceCard = new ArrayList<Card>();
    private ArrayList<String> sourceText = new ArrayList<String>(Arrays.asList("PCWorld", "TechCrunch"));

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

       for(int i=0;i<sourceText.size();i++)
       {
           System.out.println("whats up");
        Card card = new Card(this);
        identifysource=sourceText.get(i);
        card.setText(identifysource);
        sourceCard.add(card);


       }
       System.out.println(this);
       mGestureDetector = createGestureDetector(this);
       CardScrollView csvCardsView = new CardScrollView(this);
       csaAdapter cvAdapter = new csaAdapter();
       csvCardsView.setAdapter(cvAdapter);
       csvCardsView.activate();
       setContentView(csvCardsView);
       cardindex=csvCardsView.getSelectedItemPosition();

    }

private static class csaAdapter extends CardScrollAdapter
    {
        @Override
        public int findIdPosition(Object id)
        {
            return -1;
        }

        @Override
        public int findItemPosition(Object item)
        {
            return sourceCard.indexOf(item);
        }

        @Override
        public int getCount()
        {
            return sourceCard.size();
        }

        @Override
        public Object getItem(int position)
        {
            return sourceCard.get(position);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            return sourceCard.get(position).toView();
        }

    }
}

This results in the same cardindex output every time i.e 0 I tried getting the position with cvAdapter.findItemPosition() but that also returns -1 everytime.

回答1:

Implement the onClickListener from the CardScrollView. Within you'll be able to determine which item was selected.