简体   繁体   中英

Android TabLayout and ViewPager get position click item

Good evening my friend,

I did this tutorial http://www.journaldev.com/12958/android-tablayout-viewpager#comment-37790 and everythink was fine. Now i want add the function on click to listView and get the position when i click on items. Please help me.

This is the factivity_main.xml

   <?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.journaldev.tablayoutviewpager.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            style="@style/MyStyle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabGravity="fill"
            app:tabMode="fixed" />

    </android.support.design.widget.AppBarLayout>


    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />


    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

this is the ViewPager in the MainActivity

public class ViewPagerAdapter extends FragmentPagerAdapter {

    public ViewPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment = null;
        if (position == 0)
        {
            fragment = new FragmentA();
        }
        else if (position == 1)
        {
            fragment = new FragmentB();
        }
        else if (position == 2)
        {
            fragment = new FragmentC();
        }
        return fragment;
    }

    @Override
    public int getCount() {
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        String title = null;
        if (position == 0)
        {
            title = "Tab-1";
        }
        else if (position == 1)
        {
            title = "Tab-2";
        }
        else if (position == 2)
        {
            title = "Tab-3";
        }
        return title;
    }
}

this is fragment_list.xml

<?xml version="1.0" encoding="utf-8"?>

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/list"/>

this is FragmentA

public class FragmentA extends Fragment {


    ListView list;


       public FragmentA() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment, container, false);

            list = (ListView) view.findViewById(R.id.list);
            ArrayList stringList= new ArrayList();

            stringList.add("Item 1A");
            stringList.add("Item 1B");
            stringList.add("Item 1C");
            stringList.add("Item 1D");
            stringList.add("Item 1E");
            stringList.add("Item 1F");

            CustomAdapter adapter = new CustomAdapter(stringList,getActivity());
            list.setAdapter(adapter);

            return view;
        }
    }

This is CustomAdapter.java

public class CustomAdapter extends ArrayAdapter {

    private ArrayList dataSet;
    Context mContext;

    // View lookup cache
    private static class ViewHolder {
        TextView txtName;

    }

    public CustomAdapter(ArrayList data, Context context) {
        super(context, R.layout.row_item, data);
        this.dataSet = data;
        this.mContext = context;

    }

    @Nullable
    @Override
    public String getItem(int position) {
        return dataSet.get(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder viewHolder; // view lookup cache stored in tag

        if (convertView == null) {

            viewHolder = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(getContext());
            convertView = inflater.inflate(R.layout.row_item, parent, false);
            viewHolder.txtName = (TextView) convertView.findViewById(R.id.name);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        viewHolder.txtName.setText(getItem(position));
        // Return the completed view to render on screen
        return convertView;
    }
}

The MainActivity.java class

public class CustomAdapter extends ArrayAdapter {

    private ArrayList dataSet;
    Context mContext;

    // View lookup cache
    private static class ViewHolder {
        TextView txtName;

    }

    public CustomAdapter(ArrayList data, Context context) {
        super(context, R.layout.row_item, data);
        this.dataSet = data;
        this.mContext = context;

    }

    @Nullable
    @Override
    public String getItem(int position) {
        return dataSet.get(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder viewHolder; // view lookup cache stored in tag

        if (convertView == null) {

            viewHolder = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(getContext());
            convertView = inflater.inflate(R.layout.row_item, parent, false);
            viewHolder.txtName = (TextView) convertView.findViewById(R.id.name);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        viewHolder.txtName.setText(getItem(position));
        // Return the completed view to render on screen
        return convertView;
    }
}

In fragment
RecyclerViewAdapter adapter = new RecyclerViewAdapter(items,this);

In Adapter

public class RecyclerViewAdapter extends RecyclerView.Adapter {

String[] items;
private final OnItemClickListener listener;

public interface OnItemClickListener {

    void onItemClick(int item);

   }


public RecyclerViewAdapter(String[] items) {
    this.items = items;
}

@Override
public TextItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_view_list_item, parent, false);
    return new TextItemViewHolder(view);
}

@Override
public void onBindViewHolder(TextItemViewHolder holder, int position) {
    holder.bind(items[position]);
     holder.textview.setOnClickListener(new View.OnClickListener() {

      @Override public void onClick(View v) {

          listener.onItemClick(position);

    }

});

}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public int getItemCount() {
    return items.length;
}

}

and in Fragment

`

public class FragmentA extends Fragment implement RecyclerViewAdapter.OnItemClickListener {

  ...
@Override
void onItemClick(int item){

  //perform your action
     }
}

}

I am not fully familiar with the tutorial but to obtain the position you should have something similar to this.

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    int position1 = position;}
    });

My TabLayout has a fragment, and this code is in my fragment along with setting up the ListView data.

Firstly, create an interface

public interface ClickListener {
    void itemlistener(int position);
}

Secondly, put the interface to your recycler view adapter .

public class RecyclerViewAdapter extends RecyclerView.Adapter {

    String[] items;
    ClickListener clicklistener;

    public RecyclerViewAdapter(String[] items,Clicklistener clicklistener) {
        this.items = items;
        this.clicklistener = clicklistener;
    }

    ............
}

Then, use the interface function in your view holder with onClickListener.

public class TextItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    private TextView textView;


    public TextItemViewHolder(View itemView) {
        super(itemView);
        textView = (TextView) itemView.findViewById(R.id.list_item);
        itemView.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
       clicklistener.itemlistener(getAdapterPosition());    
    }
}

Next, implement the interface in your fragment . Override the method in the interface. Then you will get the position from your RecyclerView Adapter .

public class FragmentA extends Fragment implements ClickListener{

    RecyclerView recyclerView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(
                R.layout.fragment, container, false);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        String[] items = getResources().getStringArray(R.array.tab_A);
        RecyclerViewAdapter adapter = new RecyclerViewAdapter(items, this);
        recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);

    }

    @Override
        public void itemlistener(int position) {
         Toast.makeText(this, "RecyclerView position is: " + position, Toast.LENGTH_SHORT).show();
    }
}

That's it.

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