2017-12-12 9 views
0

Im 내 onloop 메서드 밖에있는 코드의 forloop 메서드에서 인덱스에 액세스 할 수있는 방법이 궁금합니다. 나는 내 onClick 메서드를 통해 cardViews를 클릭 할 때 열리는 활동을 설정할 수 있도록 색인을 가져 오려고합니다.내 onClickMethod 외부의 forloop에서 인덱스를 액세스 할 수 있습니까?

코드 :

private void setSingleEvent(GridLayout mainGrid) { 
    //Create For loop to loop through all child items in grid 
    for(int i=0; i<mainGrid.getChildCount();i++){ 
     //Casting to all cardView items 
     CardView cardView = (CardView)mainGrid.getChildAt(i); 
     final int finalI = i; 
     cardView.setOnClickListener(new View.OnClickListener(){ 
      @Override 
      public void onClick(View view) { 
       //Getting new Activity when cardView is clicked 
       if(finalI=0){ 
        Intent genre = new Intent(HomeActivity.this, Genre.class); 
        startActivity(genre); 
       } 
      } 
     }); 
    } 
+0

if (finalI == 0) *. - 오타가 원치 않는 결과를 초래하고 있다고 생각합니다. – anomeric

+0

이것은 좋은 습관이 아닙니다. 'RecyclerView'를'GridLayout'과 함께 사용하고 그것의 어댑터에'onClick'을 설정하십시오. – Kiya

답변

0

당신이 온 클릭 방식의 내부 인덱스를 액세스 할 경우, 최종해야하거나 글로벌해야 하나.

인덱스가 루프를 구동하므로 최종이 될 수 없습니다. 해결 방법은 색인을 전역으로 만듭니다.

0

이것은 매우 나쁜 습관입니다. 미안하지만 더 나은 관행을 따르는 것을 고려해야합니다. 클릭 리스너는 인터페이스를 통해 수행 할 수 있으며 어댑터 클래스에 넣고 bindView 루틴에 연결합니다. 그런 다음 호출하는 프래그먼트 또는 활동에 인터페이스를 구현하기 만하면됩니다. 어댑터의 매개 변수 중 하나로 전달하십시오.

다음은 전체가 아닌 대부분의 리사이클 뷰에 사용되는 제네릭 바인딩 어댑터의 예입니다. 그리드는 리사이클 뷰의 또 다른 형태이기 때문에이를 위해 사용했습니다.

/** * * 2011 년 5 월 23 일에 App Studio 35에서 생성되었습니다. ,

extends BaseFragment implements IBindingRecyclerView 

/*/////////////////////////////////////////////////////////////// 
// BINDING ADAPTER OVERRIDES 
*//////////////////////////////////////////////////////////////// 
@Override 
public int getRowLayoutResourceId() { 
    return R.layout.card_person; 

} 
@Override 
public int getBindingModelId() { 
    return BR.personModel; 

} 
@Override 
public void onItemClick(Object model, int position) { 
    startViewIDsForPersonActivity((PersonModel) model); 

} 
@Override 
public void onItemLongClick(Object model, int position) { 
    final PersonModel personModel = (PersonModel) model; 
    DialogInterface.OnClickListener delete = new DialogInterface.OnClickListener() { 
     @Override 
     public void onClick(DialogInterface dialog, int which) { 
      deletePerson(personModel); 

     } 
    }; 

    mIBaseActivityCallback.showDialogMessage(personModel.getFullName(), getString(R.string.confirm_delete_of_person), delete, cancel); 

} 
@Override 
public void onActionItemClick(Object model, int position) { 

} 
@Override 
public int getActionButtonResourceId(){ 
    return -1; 
} 

물론이 당신을 위해 과잉이다 : */ 공용 클래스 BindingRecyclerViewAdapter는 RecyclerView.Adapter이 그런 다음 수업 시간에 당신이 할 수 View.OnClickListener, View.OnLongClickListener {

/*/////////////////////////////////////////////////////////////// 
// MEMBERS 
*//////////////////////////////////////////////////////////////// 
private static String TAG = Globals.SEARCH_STRING + BindingRecyclerViewAdapter.class.getSimpleName(); 
private int MODEL_TAG = -124; 
private int MODEL_POSITION_TAG = -125; 
private int mRowLayoutResourceId; 
private int mBindingModelId; 
private int mActionButtonId; 
private boolean mHasActionButton; 
private ObservableArrayList<T> mList; 
private IBindingRecyclerView mIBindingRecyclerView; 


/*/////////////////////////////////////////////////////////////// 
// PROPERTIES 
*//////////////////////////////////////////////////////////////// 
/** 
* This is now how the interface needs to be set. This is taken care of in the @BindingAdapter 
* method "bind:rcvInterface" (BindingAdapterMethods). I also decided to take care of setting the 
* rowLayoutResourceId here, more as a "might as well" sort of thing, but also preventing the chance 
* of a null ref exception if we were to use mIBindingRecyclerView.getRowLayoutResourceId() and 
* mIBindingRecyclerView was null. Same goes for bindingModelId. 
* @param iBindingRecyclerView 
*/ 
public void setIBindingRecyclerView(IBindingRecyclerView iBindingRecyclerView) { 
    mIBindingRecyclerView = iBindingRecyclerView; 
    mRowLayoutResourceId = iBindingRecyclerView.getRowLayoutResourceId(); 
    mBindingModelId = iBindingRecyclerView.getBindingModelId(); 
    mActionButtonId = iBindingRecyclerView.getActionButtonResourceId(); 
    mHasActionButton = mActionButtonId > 0; 

} 
/** 
* This is how the list is set and any changes made will be notified here. If notifyDataSetChanged() 
* is not called here, then the view will not be updated with the list changes. Setting the list gets 
* taken care of in the @BindingAdapter method "bind:rcvList" (BindingAdapterMethods). Anytime the list 
* changes in the activity/fragment, it will trigger the "bind:rcvList" method, and that will call 
* setList(), thus updating the list and notifying data set changed which updates the view properly. 
* @param list 
*/ 
public void setList(ObservableArrayList list) { 
    mList = list; 
    notifyDataSetChanged(); 

} 


/*/////////////////////////////////////////////////////////////// 
// BASE CLASS OVERRIDES 
*//////////////////////////////////////////////////////////////// 
@Override 
public BindingHolder onCreateViewHolder(ViewGroup parent, int viewType) { 
    LayoutInflater inflater = LayoutInflater.from(parent.getContext()); 
    ViewDataBinding viewDataBinding = DataBindingUtil.inflate(inflater, mRowLayoutResourceId, parent, false); 
    return new BindingHolder(viewDataBinding); 

} 
@Override 
public void onBindViewHolder(BindingHolder holder, int position) { 
    T model = mList.get(position); 
    holder.binding.setVariable(mBindingModelId, model); 
    holder.binding.setVariable(BR.AMEnvironment, AMEnvironment.getInstance()); 
    holder.binding.getRoot().setTag(MODEL_TAG, model); 
    holder.binding.getRoot().setTag(MODEL_POSITION_TAG, position); 
    holder.binding.getRoot().setOnClickListener(this); 
    holder.binding.getRoot().setOnLongClickListener(this); 

    if(mHasActionButton){ 
     View btnAction = holder.binding.getRoot().findViewById(mActionButtonId); 
     btnAction.setTag(MODEL_TAG, model); 
     btnAction.setTag(MODEL_POSITION_TAG, position); 
     btnAction_onClick(btnAction); 

    } 

    holder.binding.executePendingBindings(); 

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

} 


/*/////////////////////////////////////////////////////////////// 
// CLICK LISTENERS 
*//////////////////////////////////////////////////////////////// 
@Override 
public void onClick(View v) { 
    if(mIBindingRecyclerView != null){ 
     T model = (T) v.getTag(MODEL_TAG); 
     int position = (int) v.getTag(MODEL_POSITION_TAG); 
     mIBindingRecyclerView.onItemClick(model, position); 

    } 

} 
@Override 
public boolean onLongClick(View v) { 
    if(mIBindingRecyclerView != null){ 
     T model = (T) v.getTag(MODEL_TAG); 
     int position = (int) v.getTag(MODEL_POSITION_TAG); 
     mIBindingRecyclerView.onItemLongClick(model, position); 

    } 

    return true; 

} 
public void btnAction_onClick(View btnAction){ 
    btnAction.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      T model = (T) v.getTag(MODEL_TAG); 
      int position = (int) v.getTag(MODEL_POSITION_TAG); 
      mIBindingRecyclerView.onActionItemClick(model, position); 

     } 
    }); 

} 


/*/////////////////////////////////////////////////////////////// 
// SCOPED CLASSES 
*//////////////////////////////////////////////////////////////// 
public static class BindingHolder extends RecyclerView.ViewHolder { 
    // MEMBERS 
    public ViewDataBinding binding; 

    // CONSTRUCTOR 
    public BindingHolder(ViewDataBinding viewDataBinding) { 
     super(viewDataBinding.getRoot()); 
     binding = viewDataBinding; 

    } 

} 

} 

를 구현 확장 그래서 바인딩 조각과 액션 버튼 와이어를 버릴 수는 있지만 최소한 클릭 처리를 위해 인터페이스를 사용하는 대신 그림을 가져와야합니다.