简体   繁体   English

我在哪里应该在Android中调用Interface?

[英]Where should I call Interface in android?

I am trying to call the activity method from the adaptor class using interface. 我正在尝试使用接口从适配器类中调用活动方法。 And both the activity are independent ie class which is calling adapter and the class where the method is defined. 并且这两个活动都是独立的,即调用适配器的类和定义方法的类。

Interface class 接口类

public interface AdapterCallback  {        
    int onMethodCallback();
}

Adapter class 转接器类别

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

    String[] goals;
    Context context;
    private AdapterCallback mAdapterCallback;


    public  SimpleAdapter(Context context, String[] goals)
    {
        super();
        this.context=context;
        this.goals=goals;


    }

   /* public SimpleAdapter(Context context) {

        try {

        } catch (ClassCastException e) {
            throw new ClassCastException("Activity must implement AdapterCallback.");
        }

    }*/

    @Override
    public SimpleAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.simple_item,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final SimpleAdapter.ViewHolder holder, int position) {

      holder.textView.setText(goals[position]);

      holder.textView.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {

              try {
                  mAdapterCallback = ((AdapterCallback) context);
                  int result=mAdapterCallback.onMethodCallback();
                  Toast.makeText(context,Integer.toString(result), Toast.LENGTH_SHORT).show();
              } catch (ClassCastException exception) {
                  // do something
                  Log.i("In the catch","Yes");
              }




          }
      });

    }

    @Override
    public int getItemCount() {
        return  goals.length;
    }


    public class ViewHolder extends RecyclerView.ViewHolder {

        Button textView;

        public ViewHolder(View itemView) {
            super(itemView);

            textView=(Button) itemView.findViewById(R.id.text);
        }
    }

}

Method is defined in the MainActivity.class 方法在MainActivity.class中定义

@Override
public int onMethodCallback() {
    // do something
    return 2;
}

Problem: How should I call the interface function so that indirectly it will call the function defined in the MainActivity class. 问题:我应该如何调用接口函数,以便间接地调用MainActivity类中定义的函数。

I know I need to provide the context of the MainActivity as 我知道我需要提供MainActivity的上下文

mAdapterCallback = ((AdapterCallback) context);

but where should I put this code. 但是我应该把这段代码放在哪里。

IF i put this code in the constructor then it will not get the MainActivity class context because adapter is calling from another class. 如果我将此代码放在构造函数中,则它将不会获得MainActivity类上下文,因为适配器是从另一个类调用的。

EDIT: 编辑:

public class MainActivity extends AppCompatActivity implements AdapterCallback {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

    @Override
    public int onMethodCallback() {
        // do something
        return 2;
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    public int sampleFunction()
    {
        return 2;
    }
}

EDIT 2 编辑2

Class which is calling the adaptor class 调用适配器类的类

public class OtherClass extends AppCompatActivity {

    RecyclerView recyclerView;
    SimpleAdapter simpleAdapter;
    String[]  action_name={"Swimming","Yoga","SWD","IFT","Follow Diet Plan", "Diagnostic Tests","Record Temperature","Record Blood Pressure"," Record Sugar Level","Record Weight"};

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.xtra);

        recyclerView=(RecyclerView) findViewById(R.id.recylerview);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));


        simpleAdapter=new SimpleAdapter(this, action_name);

        recyclerView.setAdapter(simpleAdapter);

    }
}
   public class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.ViewHolder> {

    String[] goals;
    Context context;
    private AdapterCallback mAdapterCallback;


    public  SimpleAdapter(Context context, String[] goals)
    {
        super();
        this.context=context;
        this.goals=goals;
    }

   /* public SimpleAdapter(Context context) {

        try {

        } catch (ClassCastException e) {
            throw new ClassCastException("Activity must implement AdapterCallback.");
        }

    }*/

    @Override
    public SimpleAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.simple_item,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final SimpleAdapter.ViewHolder holder, int position) {

        holder.textView.setText(goals[position]);

        holder.textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                try {
                    mAdapterCallback = ((AdapterCallback) context);
                    int result=mAdapterCallback.onMethodCallback();
                    Toast.makeText(context,Integer.toString(result), Toast.LENGTH_SHORT).show();
                } catch (ClassCastException exception) {
                    // do something
                    Log.i("In the catch","Yes");
                }
            }
        });

    }
    @Override
    public int getItemCount() {
        return  goals.length;
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        Button textView;
        public ViewHolder(View itemView) {
            super(itemView);
            textView=(Button) itemView.findViewById(R.id.text);
            //for entire cell
            itemView.setOnClickListener(this);
            //or only for button
            textView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            /*
            If your want clicked position you can use bellow code
             */
            //int clicked_position = getAdapterPosition();
            mAdapterCallback.onMethodCallback(clicked_position,goals[clicked_position]);
        }
    }
}

this is the way we have to use interface in android recyclerview 这是我们必须在android recyclerview中使用界面的方式

Edits 编辑

change your interface like bellow 像下面一样更改您的界面

public interface AdapterCallback  {
    void onMethodCallback(int position,String value);
}

and on your OtherClass.class like bellow 并在您的OtherClass.class上像波纹管

    public class OtherClass extends AppCompatActivity implements AdapterCallback{

    RecyclerView recyclerView;
    SimpleAdapter simpleAdapter;
    String[]  action_name={"Swimming","Yoga","SWD","IFT","Follow Diet Plan", "Diagnostic Tests","Record Temperature","Record Blood Pressure"," Record Sugar Level","Record Weight"};

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.xtra);

        recyclerView=(RecyclerView) findViewById(R.id.recylerview);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));


        simpleAdapter=new SimpleAdapter(this, action_name);

        recyclerView.setAdapter(simpleAdapter);

    }

    @Override
    public void onMethodCallback(int position, String value) {
        System.out.println(value+"    "+position);
        //start activity intent here , now you have position as well as selected value
    }
}

If you have implemented interface AdapterCallback in MainActivity then call constructor of SimpleAdapter with including a new paramenter of AdapterCallback Object. 如果您已经在MainActivity中实现了接口AdapterCallback ,则调用SimpleAdapter的构造函数,其中包括一个新的AdapterCallback Object参数。 Try with these change. 尝试这些更改。 It may helps you 可能对您有帮助

String[] goals;
Context context;
private AdapterCallback mAdapterCallback;

public  SimpleAdapter(Context context, AdapterCallback adapterCallback, String[] goals){
        super();
        this.context=context;
        this.adapterCallback = adapterCallback;
        this.goals=goals;
    }

and remove this 并删除此

mAdapterCallback = ((AdapterCallback) context);

First you have set the interface.Write a method like this in your adapter class 首先设置接口,在适配器类中写一个这样的方法

    AdapterCallback  adapterCallback ;
    public void setAdapterCallback(AdapterCallback adapterCallback){
      this.adapterCallback = adapterCallback
    } 

Now impliment and initialize the interface where you actually requires the callback. 现在隐含并初始化您实际需要回调的接口。 In your case MainActivity Do like this 在您的情况下MainActivity这样做

MainActivity extends AppCompatActivity implements AdapterCallback 

now initialize your interface like this. 现在像这样初始化您的界面。

   SimpleAdapter adpter = new SimpleAdapter()   
   adpter.setAdapterCallback(this);       // very imp step

Now send the callback like this 现在像这样发送回调

 holder.textView.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {
               if(adapterCallback  != null){
                  adapterCallback.onMethodCallback();  
              }
          }
      });

That's all you will get callback on your mainactivity.. 这就是您将在mainactivity上获得回调的全部。

Edit 编辑

I see you have your adapter set in another activity ..In that case you have to pass your interface object like this 我看到您在另一个活动中设置了适配器。在这种情况下,您必须像这样传递接口对象

AdapterCallback  adapterCallback = this;
Intent intent = new Intent(context, OtherClass.class);
intent.putExtra("interface", adapterCallback);
startActivity(intent);

And retreive it in OtherClass; 并在OtherClass中检索它;

Intent intent = getIntent();
AdapterCallback   inter = (AdapterCallback) intent.getSerializableExtra("interface");

Also change interface to serializable . 还要将接口更改为serializable。

public interface AdapterCallback  extends Serializable {
     int onMethodCallback();
}

And setInterface like this 像这样的setInterface

  simpleAdapter.setAdapterCallback(inter);

If you jsut used a fragment instead of otherclass it would have been a lot easier.. 如果您是jsut使用片段而不是otherclass的话,它会容易得多。

Edit 编辑

If both activities are independent then you can write a gettter and setter for your interface in Application class. 如果两个活动都是独立的,则可以在Application类中为接口编写getter和setter。 Set the interface from mainActivity and get the callback in your adater.. 从mainActivity设置接口,并在您的适配器中获取回调。
write this in your Application class 写在你的应用程序类

AdapterCallback  adapterCallback;
public AdapterCallback getAdapterCallback() {
    return adapterCallback;
}

public void setAdapterCallback(AdapterCallback adapterCallback) {
    this.adapterCallback = adapterCallback;
}

Write this in your Main 写在你的

((YourApplication)getApplication()). setAdapterCallback(this);

And use this method in your click 并在您的点击中使用此方法

((YourApplication) getApplication()).getAdapterCallback().onMethodCallback();

I'm not sure just a work around try, 我不确定只是尝试一下,

If u have an Util class create a method or Create a Util class and do 如果您有一个Util类,请创建一个方法或创建一个Util类,然后执行

say

 private Context mContext;
    public void setContext(Context context) {
        mContext = context;
    }

    public Context getContext(){

        return mContext;
    }

Then 然后

set the context in MainActivity 在MainActivity中设置上下文

like 喜欢

Util.setContext(MainActivity.this);

and in SimpleAdapter class use Util.getContext() and 并在SimpleAdapter类中使用Util.getContext()和

Context context = Util.getContext();
 if(context != null && context instanceof MainActivity){
    mAdapterCallback = ((AdapterCallback) context);
    int result=mAdapterCallback.onMethodCallback();
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我应该在哪里放置界面? - Where should I put interface? MVVM - 我应该在哪里调用用户位置? - MVVM - where should I call for user location? 我应该在哪里调用 Rest API 片段 - Where should I call Rest API in fragment 我应该在哪里放置@Transactional注释:在接口定义或实现类? - Where should I put @Transactional annotation: at an interface definition or at an implementing class? Android MVP我应该在哪里拥有TextWatcher - Android MVP Where should i have a TextWatcher 我应该在Android开发中使用侦听器接口或处理程序来进行事件回调吗? - Should I use a listener interface or handler for event callbacks in Android development? 我的用户界面代码应放在哪里? - Where should my user interface code be located? 我应该在哪里调用更新映射函数?我需要在异步任务之后调用它? - Where should I call my update map function?I need to call it after my Async Task? 使用Apache Thrift的第一个程序 - 我应该在哪里定义接口? 在客户端或服务器代码中 - First program with Apache Thrift - Where should I define the interface? in client or server code 我应该在哪里存储 android 中的 static 数据以最快地读取? - Where should I store the static data in android for fastest read?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM