我应该在哪里调用android中的Interface?

时间:2016-12-08 06:48:54

标签: java android interface android-arrayadapter

我试图使用interface调用适配器类中的activity方法。这两个活动都是独立的,即调用适配器的类和定义方法的类。

接口类

public interface AdapterCallback  {        
    int onMethodCallback();
}

适配器类

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);
        }
    }

}

方法在MainActivity.class中定义

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

问题: 我应该如何调用接口函数,以便间接调用MainActivity类中定义的函数。

我知道我需要提供MainActivity的上下文

mAdapterCallback = ((AdapterCallback) context);

但我应该把这段代码放在哪里。

如果我将此代码放在构造函数中,那么它将无法获取MainActivity类上下文,因为适配器正在从另一个类调用。

修改

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;
    }
}

编辑2

调用适配器类的类

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);

    }
}

4 个答案:

答案 0 :(得分:0)

   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]);
        }
    }
}

这是我们在android recyclerview中使用界面的方式

<强>编辑

更改您的界面,如下面的

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

和你的OtherClass.class一样,如bellow

    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
    }
}

答案 1 :(得分:0)

如果您在MainActivity中实现了接口 AdapterCallback ,则调用SimpleAdapter的构造函数,并包含一个新的AdapterCallback Object参数。尝试这些变化。它可能会帮助你

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;
    }

并删除此

mAdapterCallback = ((AdapterCallback) context);

答案 2 :(得分:0)

首先设置接口。在适配器类中编写这样的方法

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

现在实现并初始化您实际需要回调的界面。在你的情况下MainActivity这样做

MainActivity extends AppCompatActivity implements AdapterCallback 

现在就像这样初始化你的界面。

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

现在发送像这样的回调

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

所有你将得到你的主要活动的回调..

修改

我看到你在另一个活动中设置了适配器..在这种情况下你必须像这样传递你的接口对象

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

在OtherClass中检索它;

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

同时将接口更改为可序列化。

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

像这样的setInterface

  simpleAdapter.setAdapterCallback(inter);

如果你jsut使用了一个片段而不是其他类,那么它会更容易......

修改

如果两个活动都是独立的,那么您可以在Application类中为您的接口编写gettter和setter。从mainActivity设置界面并在adater中获取回调。
  在应用程序类

中写下这个
AdapterCallback  adapterCallback;
public AdapterCallback getAdapterCallback() {
    return adapterCallback;
}

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

将此内容写入主要

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

在点击中使用此方法

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

答案 3 :(得分:0)

我不确定只是尝试一下,

如果您有Util类创建方法或创建Util类并执行

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

    public Context getContext(){

        return mContext;
    }

然后

在MainActivity中设置上下文

喜欢

Util.setContext(MainActivity.this);

并在SimpleAdapter类中使用Util.getContext()和

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