How to refresh a view in main activity from an adapter?

喜夏-厌秋 提交于 2019-12-02 16:57:09

问题


I have a graph in main activity also I have a recycler view in main activity. Custom adapter is used for recyclerview. I have a check box and swipe layout in list item layout. in swipe layout there is a delete button.

I want to reset the graph of main activity when I check the check box or when I delete any item.

For this I created one method in main activity. And called this method in adapter onCheckedChangeListener and on click of delete.

But I am getting a null pointer exception on mBarChart. i.e . graph. I have instantiated in mBarChart in setUI method and this is called in onCreate of an activity.

resetMethod

    public void resetGraph(Context context)
{

    mBarChart.invalidate();

}

in adapter :

  Context conext;
  MainActivity mainActivity;

  mainActivity = new MainActivity();

  mainActivity.resetGraph(conext);

How to do this? Please help.. Thank you..


回答1:


In Adapter call your resetMethod this way

((MainActivity)context).resetGraph(context);



回答2:


Create a interface that implement Activity, Main activity in your case and override method and perform operation.

//Interface

public interface OnRefreshViewListner{

  public void refreshView();

}


//Main Activity
 MainActivity extends Activity implements OnRefreshViewListner
{

  //Other methods

  @Override
  public void refreshView(){

    // write refresh code here

 }

}


//Initialize Interface in adapter constructor

public class YourAdapter extends BaseAdapter {

 private OnRefreshViewListner mRefreshListner;
 public YourAdapter (Context context) {
       mRefreshListner = (OnRefreshViewListner)context; 
    }

    //call MainActivity method
    mRefreshListner.refreshView();
}



回答3:


In the adapter, you should not create a new instance of MainActivity and call resetGraph(). You should use the instance of MainActivity, that created the adapter. Send the instance of MainActivity to the adapter, new Adapter(this) and save it in adapter.




回答4:


You can change a view from the context of an adapter like this : cast context to activity. use findviewbyid method to find the view you want. initiliaze it to a variable.

View v = ((Activity)getContext()).findViewById(WHATEVER_VIEW_COMPONENT_YOU_WANT);

change the variable as you want. note. Don't forget to use the type of view that you want and cast the findview method to it.

If you want to call a method just cast the context to MainActivity and call it.



来源:https://stackoverflow.com/questions/36982209/how-to-refresh-a-view-in-main-activity-from-an-adapter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!