简体   繁体   中英

Android GridView setOnItemClickListener get TextView value

i need to get Category Id from a GridView item on Click but i don't know how to do it i can only get the position of item in the grid , 0 , 1 , 2 ... here is my code

My TextView in the XML

  <TextView
    android:id="@+id/catid"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:paddingTop="15dp"
    android:paddingBottom="15dp"
    android:layout_gravity="right"
    />

my GridView :

    final GridView gridView = (GridView) getActivity().findViewById(R.id.gridview);

    gridView.setAdapter(new MyAdapter(getActivity()));

    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // start-media code could go in fragment or adapter
            Toast.makeText(getActivity()
                    ,"position: "+position
                    +" cat id :"+gridView.getAdapter().getItem(position)
                    ,Toast.LENGTH_SHORT).show();

        }
    });
public void onItemClick(AdapterView<?> parent, View view, int position,long id)
     {
         String data=(String)parent.getItemAtPosition(position);


     }});

data contains your clicked position's data. Do what ever you want to do with that.

You have created customer adapter ie MyAdapter which may extend BaseAdapter. There is a method in it called getItemId , you can get category id from there and you just need to set that value there.

@Override
    public long getItemId(int position) {
        return items.get(position).getCatId();
    }

Now you find your catId as id in below method

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// here id will be your catId
}

if my answer helps, kindly upvote.

Try this:

 public void onItemClick(AdapterView<?> parent, View view, int position,long id)
 {
     String data=((TextView)view).getText().toString();


 }});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM