Programming

어댑터에서 통화 활동 방법

procodes 2020. 7. 29. 20:32
반응형

어댑터에서 통화 활동 방법


Activity에서 정의 된 메소드를 호출 할 수 ListAdapter있습니까?

(난을 만들고 싶어 Button에서 list's행이 버튼을 클릭하면, 그것은 활동 대응에 정의 된 방법을 수행해야합니다. 나는 세트에 시도 onClickListener내에서 ListAdapter하지만 나는 그것의 경로 무엇이 메소드를 호출하는 방법을 모르겠어요. ..)

내가 사용할 때 Activity.this.method()다음과 같은 오류가 발생합니다.

No enclosing instance of the type Activity is accessible in scope

어떤 아이디어?


그래 넌 할수있어.

어댑터에서 새 필드 추가 :

private Context mContext;

어댑터 생성자에서 다음 코드를 추가하십시오.

public AdapterName(......, Context context) {
  //your code.
  this.mContext = context;
}

어댑터의 getView (...)에서 :

Button btn = (Button) convertView.findViewById(yourButtonId);
btn.setOnClickListener(new Button.OnClickListener() {
  @Override
  public void onClick(View v) {
    if (mContext instanceof YourActivityName) {
      ((YourActivityName)mContext).yourDesiredMethod();
    }
  }
});

코드, 활동 등을 볼 수있는 자신의 클래스 이름으로 대체하십시오.

둘 이상의 활동에 동일한 어댑터를 사용해야하는 경우 다음을 수행하십시오.

인터페이스 만들기

public interface IMethodCaller {
    void yourDesiredMethod();
}

이 메소드 호출 기능이 필요한 활동에서이 인터페이스를 구현하십시오.

그런 다음 어댑터 getView ()에서 다음과 같이 호출하십시오.

Button btn = (Button) convertView.findViewById(yourButtonId);
btn.setOnClickListener(new Button.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (mContext instanceof IMethodCaller) {
            ((IMethodCaller) mContext).yourDesiredMethod();
        }
    }
});

끝났습니다. 이 호출 메커니즘이 필요하지 않은 활동에이 어댑터를 사용해야하는 경우 코드가 실행되지 않습니다 (확인에 실패한 경우).


이 방법으로 할 수 있습니다 :

인터페이스 선언 :

public interface MyInterface{
    public void foo();
}

당신의 활동이 그것을 구현하게하십시오 :

public class MyActivity extends Activity implements MyInterface{
    public void foo(){
        //do stuff
    }
}

그런 다음 활동을 ListAdater로 전달하십시오.

public MyAdapter extends BaseAdater{
    private MyInterface listener;

    public MyAdapter(MyInterface listener){
        this.listener = listener;
    }
}

어댑터의 어딘가에서 해당 Activity 메소드를 호출 해야하는 경우 :

listener.foo();

실물:

현재 답변을 이해하지만 더 명확한 예가 필요했습니다. 다음은 Adapter(RecyclerView.Adapter) 및와 함께 사용한 예제입니다 Activity.

당신의 활동에서 :

이것은 interface우리가 가지고 있는 것을 구현할 Adapter입니다. 이 예에서는 사용자가의 항목을 클릭하면 호출됩니다 RecyclerView.

public class MyActivity extends Activity implements AdapterCallback {

    private MyAdapter myAdapter;

    @Override
    public void onMethodCallback() {
       // do something
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        myAdapter = new MyAdapter(this);
    }
}

어댑터에서 :

In the Activity, we initiated our Adapter and passed this as an argument to the constructer. This will initiate our interface for our callback method. You can see that we use our callback method for user clicks.

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

    private AdapterCallback adapterCallback;

    public MyAdapter(Context context) {
        try {
            adapterCallback = ((AdapterCallback) context);
        } catch (ClassCastException e) {
            throw new ClassCastException("Activity must implement AdapterCallback.", e);
        }
    }

    @Override
    public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, int position) {
        // simple example, call interface here
        // not complete
        viewHolder.itemView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    adapterCallback.onMethodCallback();
                } catch (ClassCastException e) {
                   // do something
                }
            }
        });
    }

    public static interface AdapterCallback {
        void onMethodCallback();
    }
}

Basic and simple.

In your adapter simply use this.

((YourParentClass) context).functionToRun();


One more way is::

Write a method in your adapter lets say public void callBack(){}.

Now while creating an object for adapter in activity override this method. Override method will be called when you call the method in adapter.

Myadapter adapter = new Myadapter() {
  @Override
  public void callBack() {
    // dosomething
  }
};

For Kotlin:

In your adapter, simply call

(context as Your_Activity_Name).yourMethod()

if (parent.getContext() instanceof yourActivity) {
  //execute code
}

this condition will enable you to execute something if the Activity which has the GroupView that requesting views from the getView() method of your adapter is yourActivity

NOTE : parent is that GroupView

참고URL : https://stackoverflow.com/questions/12142255/call-activity-method-from-adapter

반응형