1

I have a PopupWindow which contains a RecyclerView filled with items. I want to dismiss the PopupWindow after selecting an item in the recycleview. I know it has to be implemented with a interface, but not quite sure on how to do it in the code. Right now the items are displaying in the popupwindow and I could get the items printed in toast. It will be helpful if anybody could look to my code and guide me.

Activity.java

public class SetupActivity extends AppCompatActivity {


private ImageView imageVProfileSmall;
private RequestQueue requestQueue2;
private RecyclerView mallRecyclerView;
private MallAdapter mallRecyclerAdapter;
List<ModelMall> newMallModels = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_setup);
    initViews();
    EditText popupButton = findViewById(R.id.editTextMall);
    popupButton.setInputType(InputType.TYPE_NULL);
    popupButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            showPopup(v);
        }
    });
}


private void initViews() {
    imageVProfileSmall = findViewById(R.id.profileImg);
}

private void GET_MALL_WEB_CALL() {

    String HTTP_SERVER_URL = "http://GetMall";
    JsonArrayRequest jsArrRequest = new JsonArrayRequest
            (Request.Method.GET, HTTP_SERVER_URL, null, new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    GET_MALL_PARSE(response);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // TODO Auto-generated method stub
                    Log.i("ERROR", "Event Web call Error");
                }
            }) {

        //This is for Headers If You Needed
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> params = new HashMap<String, String>();
            params.put("Content-Type", "application/x-www-form-urlencoded");
            params.put("Authorization", "Bearer " + getFromSP("etAt"));
            return params;
        }

    };
    jsArrRequest.setRetryPolicy(new DefaultRetryPolicy(
            240000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    if (requestQueue2 == null) {
        requestQueue2 = Volley.newRequestQueue(this);
        requestQueue2.add(jsArrRequest);
    } else {
        requestQueue2.add(jsArrRequest);
    }
}

public void clear() {
    int size = newMallModels.size();
    newMallModels.clear();
    Log.i("LOL", String.valueOf(size));
}


public void GET_MALL_PARSE(JSONArray array) {
    clear();
    for (int i = 0; i < array.length(); i++) {
        ModelMall GetMallDataModel = new ModelMall();
        Log.i("SUCCESS", "Event web call success");
        JSONObject json = null;
        try {
            json = array.getJSONObject(i);
            GetMallDataModel.setMallId(json.getString("$id"));//
            GetMallDataModel.setMallName(json.getString("Resourcetype_en"));//
            newMallModels.add(GetMallDataModel);
        } catch (JSONException e) {

            e.printStackTrace();
        }
    }
    if (array.length() != 0) {
        String strArrayLen = String.valueOf(array.length());
        mallRecyclerAdapter.updateModels(newMallModels);

    }
}


public void showPopup(View view){


    //Create a View object yourself through inflater
    LayoutInflater inflater = (LayoutInflater) view.getContext().getSystemService(view.getContext().LAYOUT_INFLATER_SERVICE);
    View popupView = inflater.inflate(R.layout.layout_mall_recycler, null);

    //Specify the length and width through constants
    int width = LinearLayout.LayoutParams.MATCH_PARENT;
    int height = LinearLayout.LayoutParams.MATCH_PARENT;

    //Make Inactive Items Outside Of PopupWindow
    boolean focusable = true;

    //Create a window with our parameters
    final PopupWindow popupWindow = new PopupWindow(popupView, width, height, focusable);

    //Set the location of the window on the screen
    popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);

    //Initialize the elements of our window

    LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
    mallRecyclerView = popupView.findViewById(R.id.recyclerView);
    mallRecyclerView.setLayoutManager(layoutManager);
    mallRecyclerAdapter = new MallAdapter(this);
    mallRecyclerView.setAdapter(mallRecyclerAdapter);

    GET_MALL_WEB_CALL();

    //Handler for clicking on the inactive zone of the window

    popupView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            //Close the window when clicked
            popupWindow.dismiss();
            return true;
        }
    });
}


private void saveInSp(String key, String value) {
    SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString(key, value);
    editor.apply();
}

private String getFromSP(String key) {
    SharedPreferences preferences = this.getSharedPreferences("PROJECT_NAME", Context.MODE_PRIVATE);
    return preferences.getString(key, "");
}

@Override
protected void onResume() {
    super.onResume();
}


}

Adapter.java

public class MallAdapter extends RecyclerView.Adapter<MallAdapter.ViewHolder>   {

private Context context;
private final List<ModelMall> mallDataModels;

public MallAdapter(Context context) {
    super();
    this.context = context;
    this.mallDataModels = new ArrayList<ModelMall>();
}

public void updateModels(List<ModelMall> newModels) {
    mallDataModels.clear();
    mallDataModels.addAll(newModels);
    notifyDataSetChanged();
}

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

@Override
public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
    final ModelMall dataAdapter = mallDataModels.get(position);
    viewHolder.tVMallName.setText(dataAdapter.getMallName());
    saveInSp("SelectedMallName", String.valueOf(dataAdapter.getMallId()));
    
    viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Toast.makeText(v.getContext(), dataAdapter.getMallName(), Toast.LENGTH_SHORT).show();
            saveInSp("selectedMall", dataAdapter.getMallName());
        }
    });
}

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


class ViewHolder extends RecyclerView.ViewHolder {

    private TextView tVMallName;

    public ViewHolder(View itemView) {
        super(itemView);
        tVMallName = itemView.findViewById(R.id.textMallName);

    }
}
}
Kumza Ion
  • 353
  • 2
  • 12
  • 1
    There are many tutorials and similar questions in stackoverflow. You need only a few second search. I refer you to https://stackoverflow.com/a/49969478/3146806 , but there is more examples! – Reyhane Farshbaf Oct 12 '22 at 10:01

1 Answers1

1

Adapter

public class MallAdapter extends RecyclerView.Adapter<MallAdapter.ViewHolder>   {

private Context context;
private final List<ModelMall> mallDataModels;
private PopupWindowCloseListener popupWindowCloseListener;

public MallAdapter(Context context,PopupWindowCloseListener popupWindowCloseListener) {
    super();
    this.context = context;
    this.mallDataModels = new ArrayList<ModelMall>();
this.popupWindowCloseListener =popupWindowCloseListener
}

public void updateModels(List<ModelMall> newModels) {
    mallDataModels.clear();
    mallDataModels.addAll(newModels);
    notifyDataSetChanged();
}

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

@Override
public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
    final ModelMall dataAdapter = mallDataModels.get(position);
    viewHolder.tVMallName.setText(dataAdapter.getMallName());
    saveInSp("SelectedMallName", String.valueOf(dataAdapter.getMallId()));
    
    viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
popupWindowCloseListener.closeWindow();

            Toast.makeText(v.getContext(), dataAdapter.getMallName(), Toast.LENGTH_SHORT).show();
            saveInSp("selectedMall", dataAdapter.getMallName());
        }
    });
}

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


class ViewHolder extends RecyclerView.ViewHolder {

    private TextView tVMallName;

    public ViewHolder(View itemView) {
        super(itemView);
        tVMallName = itemView.findViewById(R.id.textMallName);

    }
}


interface PopupWindowCloseListener{  

void closeWindow();  
}  
}

  1. class implements listener

    public class SetupActivity extends AppCompatActivity implements PopupWindowCloseListener
    
  2. make popupWindow as global variable

    PopupWindow popupWindow ;
    
    popupWindow= new PopupWindow(popupView, width, height, focusable)
    
  3. set adapter

     mallRecyclerAdapter = new MallAdapter(this, this)
    
  4. override method close the popup

        public void closeWindow() {
    
        popupWindow.dismiss();
    
        }
    
sasikumar
  • 12,540
  • 3
  • 28
  • 48