2017-12-30 76 views
0

여기서, 을 RecyclerView 항목에 추가하는 것과 관련하여 많은 정보를 찾을 수 있습니다. 나는 하나의 상황에 맞는 메뉴 버튼을 원하고 나는 그것을 이런 식으로 구현 한 :플로팅 상황에 맞는 메뉴 RecyclerView

itemView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() { 
      @Override 
      public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { 
       MenuItem delete = menu.add(0, v.getId(), 0, "Delete"); 
       delete.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { 
        @Override 
        public boolean onMenuItemClick(MenuItem item) { 
         int position = getAdapterPosition(); 
         long id = mUploads.get(position).getId(); 
         if (position != RecyclerView.NO_POSITION) { 
          mListener.onDeleteClick(position, id); 
         } 
         return true; 
        } 
       }); 

      } 
     }); 

이 다음이 인터페이스의 메소드를 호출 그러나

@Override 
public void onDeleteClick(int position, long id) { 
    Toast.makeText(this, "position: " + position + " ID: " + id, Toast.LENGTH_SHORT).show(); 
} 

을,이 모두가 매우 지저분한보고 궁금 그 접근 방식이됩니다 나중에 문제가 발생합니다.

+0

컨텍스트 메뉴를 사용 하시겠습니까? 커스텀'DialogFragment'는 훨씬 더 많은 제어와 유연성을 제공합니다. 물론 더 많은 코드가 필요하지만'DialogFragment'로 쉽게 재사용 할 수 있습니다. – Barns

+0

아니요, 컨텍스트 메뉴가 필요하지 않습니다. 저는 이것이 올바른 접근 방식 일 것이라고 생각했습니다. 하지만 이제 DialogFragment가 좋게 들리 네요. –

+0

'DialogFragment' 예제를 게시 할 것입니다. – Barns

답변

0

사용자 지정 대화 상자를 자주 사용하므로 DialogFragment을 사용합니다. 이 대화 상자에는 "확인"및 "취소"버튼이 있습니다. 필요하지 않은 버튼은 제거 할 수 있습니다.

사용자 지정 DialogFragment "fragment_submit_cancel_dialog"에 대한 XML 레이아웃을 만들어야합니다. 자신의 디자인을 만들 수 있기 때문에 대화 상자의 모양에 많은 유연성을 제공합니다. 다음은 간단한 예입니다. 필요에 따라 이미지 나 목록을 추가 할 수도 있습니다.

implements OkCancelDialogFragment.OkCancelDialogListener{ 

청취자 방법 추가 :

@Override 
public void onFinishOkCancelDialog(boolean submit) { 
    if(submit){ 
     // Do what you need here 
    } 
} 

콜이 같은 DialogFragment :

을 당신이이 DialogFragment이를 추가해야합니다 호출 활동에

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


    <TextView 
     android:id="@+id/tvTitle" 
     android:text="Title" 
     style="@style/alert_dialog_title" 
     /> 

    <TextView 
     android:id="@+id/tvMessage" 
     android:text="MyMessage" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:paddingLeft="10dp" 
     android:paddingRight="10dp" 
     android:layout_below="@id/tvTitle" 
     android:layout_centerInParent="true" 
     android:layout_marginTop="15dp" 
     /> 

</RelativeLayout> 

private void startOkDialog(){ 
    String title = "What ever you want as a Title"; 
    String mess = "Your Message!"; 
    OkCancelDialogFragment dialog = OkCancelDialogFragment.newInstance(title, mess); 
    show(getFragmentManager(), "OkDialogFragment"); 
} 

이제 사용자 정의 대화 상자 조각에 대한 코드 :

public class OkCancelDialogFragment extends DialogFragment { 

    private static final String ARG_TITLE = "title"; 
    private static final String ARG_MESSAGE = "message"; 

    Context context = null; 

    private String title; 
    private String message; 
    private boolean submitData = false; 

    private OkCancelDialogListener mListener; 

    public OkCancelDialogFragment() { 
    } 

    public static OkCancelDialogFragment newInstance(String title, String message) { 
     OkCancelDialogFragment fragment = new OkCancelDialogFragment(); 
     Bundle args = new Bundle(); 
     args.putString(ARG_TITLE, title); 
     args.putString(ARG_MESSAGE, message); 
     fragment.setArguments(args); 
     return fragment; 
    } 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     if (getArguments() != null) { 
      title = getArguments().getString(ARG_TITLE); 
      message = getArguments().getString(ARG_MESSAGE); 
     } 
    } 

    @Override 
    public Dialog onCreateDialog(Bundle saveIntsanceState){ 

     context = getActivity(); 

     AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 

     LayoutInflater inflater = getActivity().getLayoutInflater(); 

     View rootView = inflater.inflate(R.layout.fragment_submit_cancel_dialog, null, false); 
     final TextView titleView = (TextView)rootView.findViewById(R.id.tvTitle); 
     final TextView messView = (TextView)rootView.findViewById(R.id.tvMessage); 

     titleView.setText(title); 
     messView.setText(message); 

     builder.setView(rootView) 
       .setPositiveButton(R.string.button_Ok, new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface dialog, int which) { 

         submitData = true; 
         //The onDetach will call the Listener! Just in case the user taps the back button 
        } 
       }) 
       .setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface dialog, int which) { 
         submitData = false; 
        } 
       }); 
     return builder.create(); 
    } 


    @Override 
    public void onAttach(Context context) { 
     super.onAttach(context); 
     try { 
      if(mListener == null) mListener = (OkCancelDialogListener) context; 
     } 
     catch (Exception ex){ 
      throw new RuntimeException(context.toString() 
        + " must implement OnFragmentInteractionListener"); 
     } 
    } 

    @Override 
    public void onDetach() { 
     super.onDetach(); 
     mListener.onFinishOkCancelDialog(submitData); 
     mListener = null; 
    } 


    public interface OkCancelDialogListener { 
     void onFinishOkCancelDialog(boolean submit); 
    } 

} 

이 그냥 구현 알려 방법에 대한 질문이있을 경우.