Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/231.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何使用addOnItemTouchListener在RecyclerView中创建上下文菜单_Android_Android Recyclerview_Contextmenu_Android Contextmenu - Fatal编程技术网

Android 如何使用addOnItemTouchListener在RecyclerView中创建上下文菜单

Android 如何使用addOnItemTouchListener在RecyclerView中创建上下文菜单,android,android-recyclerview,contextmenu,android-contextmenu,Android,Android Recyclerview,Contextmenu,Android Contextmenu,当用户长时间单击时,如何使用addOnItemTouchListener在RecyclerView中创建上下文菜单 我有这样的代码 public class AllDataFragment extends Fragment{ List<GetDataAdapterRiwayat> GetDataAdapter1; RecyclerView recyclerView; RecyclerView.LayoutManager recyclerViewlayou

当用户长时间单击时,如何使用
addOnItemTouchListener
RecyclerView
中创建上下文菜单

我有这样的代码

public class AllDataFragment extends Fragment{

    List<GetDataAdapterRiwayat> GetDataAdapter1;

    RecyclerView recyclerView;

    RecyclerView.LayoutManager recyclerViewlayoutManager;
    private static final String TAG = MainActivity.class.getSimpleName();

    RecyclerView.Adapter recyclerViewadapterRiwayat;

    String FIXURL = "http://192.168.43.139/AndroidFileUpload/";
    String GET_JSON_DATA_HTTP_URL = FIXURL+"GetAllData.php";
    String JSON_ID_TEMPAT_PERCETAKAN = "id_tempat_percetakan";
    String JSON_NAMA_PERCETAKAN = "nama_percetakan";
    String JSON_LATITUDE = "latitude";
    String JSON_LONGITUDE = "longitude";
    String JSON_GAMBAR = "gambar";
    String JSON_STATUS = "status";
    String JSON_EMAIL1 = "email1";
    String JSON_EMAIL2 = "email2";
    String JSON_EMAIL3 = "email3";
    SessionManager session;
    RequestQueue requestQueue ;
    String email;

    public AllDataFragment() {
        // Required empty public constructor
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        GetDataAdapter1 = new ArrayList<>();

        recyclerView = (RecyclerView) getView().findViewById(R.id.recyclerview2);

        recyclerView.setHasFixedSize(true);

        recyclerViewlayoutManager = new LinearLayoutManager(getActivity());

        recyclerView.setLayoutManager(recyclerViewlayoutManager);
        JSON_DATA_WEB_CALL();
        Log.d(TAG, "acoba nih1 : ");
        recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity().getApplicationContext(), recyclerView, new RecyclerTouchListener.ClickListener() {
            @Override
            public void onClick(View view, int position) {
                GetDataAdapterRiwayat GetDataAdapterRiwayat = GetDataAdapter1.get(position);
                Log.d(TAG, "acoba nih3 : ");
                Intent myIntent = new Intent(getActivity(), DetailRiwayatActivity.class);
                myIntent.putExtra("Gambar",GetDataAdapterRiwayat.getGambar());// getDataAdapter1 in your case
                myIntent.putExtra("IdTempatPercetakan",GetDataAdapterRiwayat.getIdTempatPercetakan());// getDataAdapter1 in your case
                myIntent.putExtra("NamaPercetakan",GetDataAdapterRiwayat.getNamaPercetakan());// getDataAdapter1 in your case
                myIntent.putExtra("Latitude",GetDataAdapterRiwayat.getLatitude());// getDataAdapter1 in your case
                myIntent.putExtra("Longitude",GetDataAdapterRiwayat.getLongitude());// getDataAdapter1 in your case
                myIntent.putExtra("Status",GetDataAdapterRiwayat.getStatus());// getDataAdapter1 in your case
                myIntent.putExtra("Email1",GetDataAdapterRiwayat.getEmail1());// getDataAdapter1 in your case
                myIntent.putExtra("Email2",GetDataAdapterRiwayat.getEmail2());// getDataAdapter1 in your case
                myIntent.putExtra("Email3",GetDataAdapterRiwayat.getEmail3());// getDataAdapter1 in your case
                startActivity(myIntent);

            }

            @Override
            public void onLongClick(View view, int position) {

            }
        }));
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        // Menu Item Clicked!
        return true;
    }

    public void JSON_DATA_WEB_CALL() {
        setSessionManager();
        CustomJsonArrayRequest request = new CustomJsonArrayRequest (GET_JSON_DATA_HTTP_URL  + "?&email="+email,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        JSON_PARSE_DATA_AFTER_WEBCALL(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
        requestQueue = Volley.newRequestQueue(getActivity());
        requestQueue.add(request);
    }

    public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
        for(int i = 0; i<array.length(); i++) {

            GetDataAdapterRiwayat GetDataAdapter2 = new GetDataAdapterRiwayat();

            JSONObject json = null;
            try {

                json = array.getJSONObject(i);
                GetDataAdapter2.setIdTempatPercetakan(json.getString(JSON_ID_TEMPAT_PERCETAKAN));
                GetDataAdapter2.setNamaPercetakan(json.getString(JSON_NAMA_PERCETAKAN));
                GetDataAdapter2.setLatitude(json.getString(JSON_LATITUDE));
                GetDataAdapter2.setLongitude(json.getString(JSON_LONGITUDE));
                GetDataAdapter2.setGambar(json.getString(JSON_GAMBAR));
                GetDataAdapter2.setStatus(json.getString(JSON_STATUS));
                GetDataAdapter2.setEmail1(json.getString(JSON_EMAIL1));
                GetDataAdapter2.setEmail2(json.getString(JSON_EMAIL2));
                GetDataAdapter2.setEmail3(json.getString(JSON_EMAIL3));
            } catch (JSONException e) {

                e.printStackTrace();
            }
            GetDataAdapter1.add(GetDataAdapter2);
        }

        recyclerViewadapterRiwayat = new RecyclerViewAdapterRiwayat(GetDataAdapter1, getActivity());

        recyclerView.setAdapter(recyclerViewadapterRiwayat);
    }

    private void setSessionManager() {
        session = new SessionManager(getActivity().getApplicationContext());
        session.checkLogin();

        // get user data from session
        HashMap<String, String> user = session.getUserDetails();
        // email
        email = user.get(SessionManager.KEY_EMAILUSER);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.activity_all_data, container, false);
    }

    @Override
    public void onClick(View v) {

    }

}
公共类AllDataFragment扩展了片段{
列出GetDataAdapter1;
回收视图回收视图;
RecyclerView.LayoutManager recyclerViewlayoutManager;
私有静态最终字符串标记=MainActivity.class.getSimpleName();
适配器RecycleWebAdapterWayAt;
字符串FIXURL=”http://192.168.43.139/AndroidFileUpload/";
字符串GET\u JSON\u DATA\u HTTP\u URL=FIXURL+“GetAllData.php”;
字符串JSON_ID_TEMPAT_PERCETAKAN=“ID_TEMPAT_PERCETAKAN”;
字符串JSON_NAMA_PERCETAKAN=“NAMA_PERCETAKAN”;
字符串JSON_LATITUDE=“LATITUDE”;
字符串JSON_LONGITUDE=“LONGITUDE”;
字符串JSON_GAMBAR=“GAMBAR”;
字符串JSON_STATUS=“STATUS”;
字符串JSON_EMAIL1=“EMAIL1”;
字符串JSON_EMAIL2=“EMAIL2”;
字符串JSON_EMAIL3=“EMAIL3”;
会话管理器会话;
请求队列请求队列;
字符串电子邮件;
公共AllDataFragment(){
//必需的空公共构造函数
}
@凌驾
已创建ActivityState上的公共无效(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
GetDataAdapter1=新的ArrayList();
recyclerView=(recyclerView)getView().findViewById(R.id.recyclerview2);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager=新的LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(recyclerViewlayoutManager);
JSON_DATA_WEB_CALL();
Log.d(标签“acoba nih1”);
recyclerView.addOnItemTouchListener(新的RecyclerTouchListener(getActivity().getApplicationContext(),recyclerView,新的RecyclerTouchListener.ClickListener()){
@凌驾
公共void onClick(视图,int位置){
GetDataAdapterRiwayat GetDataAdapterRiwayat=GetDataAdapter1.get(位置);
Log.d(标签“acoba nih3:”);
Intent myIntent=新的Intent(getActivity(),detailriwayataActivity.class);
myIntent.putExtra(“Gambar”,GetDataAdapterRiwayat.getGambar());//getDataAdapter1
myIntent.putExtra(“IdTempatPercetakan”,GetDataAdapterRiwayat.getIdTempatPercetakan());//在本例中为getDataAdapter1
myIntent.putExtra(“NamaPercetakan”,GetDataAdapterRiwayat.getNamaPercetakan());//在本例中为getDataAdapter1
myIntent.putExtra(“纬度”,GetDataAdapterRiwayat.getLatitude());//在您的例子中是getDataAdapter1
myIntent.putExtra(“经度”,GetDataAdapterRiwayat.getLongitude());//在本例中为getDataAdapter1
myIntent.putExtra(“Status”,GetDataAdapterRiwayat.getStatus());//getDataAdapter1
myIntent.putExtra(“Email1”,GetDataAdapterRiwayat.getEmail1());//在您的例子中是getDataAdapter1
myIntent.putExtra(“Email2”,GetDataAdapterRiwayat.getEmail2());//在您的示例中为getDataAdapter1
myIntent.putExtra(“Email3”,GetDataAdapterRiwayat.getEmail3());//在您的例子中是getDataAdapter1
星触觉(myIntent);
}
@凌驾
仅长按公共无效(视图,int位置){
}
}));
}
@凌驾
公共布尔onMenuItemClick(菜单项){
//菜单项点击!
返回true;
}
public void JSON_DATA_WEB_CALL(){
setSessionManager();
CustomJsonArrayRequest请求=新的CustomJsonArrayRequest(获取JSON数据HTTP URL+?&email=“+email,
新的Response.Listener(){
@凌驾
公共void onResponse(JSONArray响应){
JSON在WEBCALL之后解析数据(响应);
}
},
新的Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
}
});
requestQueue=Volley.newRequestQueue(getActivity());
添加(请求);
}
public void JSON\u解析\u数据\u WEBCALL之后(JSONArray数组){
对于(int i=0;i请尝试一下:

注意:请确保将其添加到适配器类

在RecyclerView适配器布局中添加一个
ImageButton
,其id类似。。
ivOverflowIcon

内部适配器类

ImageButton buttonViewOption;
内部
ViewHolder(视图v)

将此添加到菜单: res/menu/mycontextmenu.xml

    <?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/menu1"
        android:title="Menu 1" />

    <item
        android:id="@+id/menu2"
        android:title="Menu 2" />

    <item
        android:id="@+id/menu3"
        android:title="Menu 3" />


</menu>

步骤1:在MainActivityClass.java中

private RecyclerView recyclerSavedHotel;

private ArrayList<Integer> totalHotel;
private ArrayList<String> nameCity;

TextView tvNoSavedHotel;
RecyclerView.Adapter adapter;

private static final String TAG = "SavedHotelClass";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    nameCity = new ArrayList();
    totalHotel = new ArrayList();

    nameCity.add("Ahmedabad");
    nameCity.add("Bhavnagar");

    nameCity.add("Mahuva");
    nameCity.add("Pune");

    nameCity.add("Bhavnagar");
    nameCity.add("Bhopal");

    nameCity.add("Rojkot");
    nameCity.add("Mahuva");

    nameCity.add("Agra");
    nameCity.add("Vadodra");

    totalHotel.add(1);
    totalHotel.add(2);

    totalHotel.add(4);
    totalHotel.add(6);

    totalHotel.add(8);
    totalHotel.add(20);

    totalHotel.add(11);
    totalHotel.add(23);

    totalHotel.add(21);
    totalHotel.add(3);

    if (nameCity.isEmpty() || totalHotel.isEmpty()) {
        tvNoSavedHotel.setVisibility(View.VISIBLE);
    }

    initContext();
}

private void initContext() {
    recyclerSavedHotel = (RecyclerView) findViewById(R.id.recyclerview_save_hotel);
    recyclerSavedHotel.setHasFixedSize(true);

    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerSavedHotel.setLayoutManager(layoutManager);

    adapter = new RecyclerViewAdapter(nameCity, totalHotel);
    recyclerSavedHotel.setAdapter(adapter);


}
private RecyclerView recyclerSavedHotel;
私人ArraylistTotalHotel;
私人ArrayList名称城市;
特克斯维尤电视台酒店;
RecyclerView.适配器;
私有静态最终字符串TAG=“SavedHotelClass”;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
nameCity=newarraylist();
totalHotel=新ArrayList();
名称城市。添加(“艾哈迈达巴德”);
名称城市。添加(“Bhavnagar”);
名称城市。添加(“Mahuva”);
名称城市。添加(“普纳”);
名称城市。添加(“Bhavnagar”);
名称城市。添加(“博帕尔”);
名称城市。添加(“Rojkot”);
名称城市。添加(“Mahuva”);
名称城市。添加(“Agra”);
名称城市。添加(“瓦多德拉”);
totalHotel.add(1);
totalHotel.add(2);
totalHotel.add(4);
totalHotel.add(6);
totalHotel.add(8);
totalHotel.add(20);
totalHotel.add(11);
totalHotel.add(23);
totalHotel.add(21);
totalHotel.add(3);
if(nameCity.isEmpty()| | totalHotel.isEmpty()){
tvosavedthotel.setVisibility(View.VISIBLE);
}
initContext();
}
私有void initContext(){
recyclerSavedHotel=(RecyclerView)findViewById(R.id.RecyclerView\u save\u酒店);
recyclerSavedHotel.setHasFixedSize(真实);
holder.buttonViewOption.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //creating a popup menu
                PopupMenu popup = new PopupMenu(mCtx, holder.buttonViewOption);
                //inflating menu from xml resource
                popup.inflate(R.menu.mycontextmenu);
                //adding click listener
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.menu1:
                                //handle menu1 click
                                break;
                            case R.id.menu2:
                                //handle menu2 click
                                break;
                            case R.id.menu3:
                                //handle menu3 click
                                break;
                        }
                        return false;
                    }
                });
                //displaying the popup
                popup.show();

            }
        });
private RecyclerView recyclerSavedHotel;

private ArrayList<Integer> totalHotel;
private ArrayList<String> nameCity;

TextView tvNoSavedHotel;
RecyclerView.Adapter adapter;

private static final String TAG = "SavedHotelClass";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    nameCity = new ArrayList();
    totalHotel = new ArrayList();

    nameCity.add("Ahmedabad");
    nameCity.add("Bhavnagar");

    nameCity.add("Mahuva");
    nameCity.add("Pune");

    nameCity.add("Bhavnagar");
    nameCity.add("Bhopal");

    nameCity.add("Rojkot");
    nameCity.add("Mahuva");

    nameCity.add("Agra");
    nameCity.add("Vadodra");

    totalHotel.add(1);
    totalHotel.add(2);

    totalHotel.add(4);
    totalHotel.add(6);

    totalHotel.add(8);
    totalHotel.add(20);

    totalHotel.add(11);
    totalHotel.add(23);

    totalHotel.add(21);
    totalHotel.add(3);

    if (nameCity.isEmpty() || totalHotel.isEmpty()) {
        tvNoSavedHotel.setVisibility(View.VISIBLE);
    }

    initContext();
}

private void initContext() {
    recyclerSavedHotel = (RecyclerView) findViewById(R.id.recyclerview_save_hotel);
    recyclerSavedHotel.setHasFixedSize(true);

    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerSavedHotel.setLayoutManager(layoutManager);

    adapter = new RecyclerViewAdapter(nameCity, totalHotel);
    recyclerSavedHotel.setAdapter(adapter);


}
private ArrayList<String> nameCity;
private ArrayList<Integer> totalHotel;

public RecyclerViewAdapter(ArrayList<String> nameCity, ArrayList<Integer> totalHotel) {
    this.nameCity = nameCity;
    this.totalHotel = totalHotel;

}

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


}

@Override
public void onBindViewHolder(RecyclerViewAdapter.ViewHolder holder, int position) {
    holder.tvCityname.setText(nameCity.get(position));
    holder.tvTotalHotel.setText(totalHotel.get(position).toString());

}

@Override
public int getItemCount() {
    return nameCity.size();
}


public class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
    TextView tvCityname, tvTotalHotel;

    public ViewHolder(View itemView) {
        super(itemView);
        tvCityname = (TextView) itemView.findViewById(R.id.tv_saved_hotel_city_name);
        tvTotalHotel = (TextView) itemView.findViewById(R.id.tv_total_saved_hotel);
        itemView.setOnCreateContextMenuListener(this);

    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        menu.setHeaderTitle("Select The Action");
        menu.add(0, v.getId(), 0, "Call");//groupId, itemId, order, title
        menu.add(0, v.getId(), 0, "SMS");
    }
}
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/cardview_saved_hotel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardUseCompatPadding="true"
app:cardBackgroundColor="@color/colorWhite">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tv_saved_hotel_city_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#000"
            android:textSize="20sp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <ImageView
                android:layout_width="15dp"
                android:layout_height="15dp"
                android:layout_marginRight="5dp"
                android:layout_marginTop="3dp"
                android:src="@mipmap/ic_heart_red" />

            <TextView
                android:id="@+id/tv_total_saved_hotel"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="5dp" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Hotel saved" />

        </LinearLayout>

    </LinearLayout>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:src="@mipmap/ic_next_black" />

</LinearLayout>
 <android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerview_save_hotel"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

</android.support.v7.widget.RecyclerView>