如何从适配器刷新 main activity 中的视图?

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

我在主 activity 中有一个图表,我在主 activity 中也有一个回收视图。自定义适配器用于 recyclerview。我在列表项布局中有一个复选框和滑动布局。在滑动布局中有一个删除按钮。

我想在选中复选框或删除任何项目时重置主图 activity。

为此,我在 main activity 中创建了一个方法。并在适配器 onCheckedChangeListener 和点击删除时调用此方法。

但是我在 mBarChart 上遇到空指针异常。 IE 。图形。我已经在 setUI 方法中的 mBarChart 中实例化,这在 activity.

的 onCreate 中调用

重置方法

    public void resetGraph(Context context)
{

    mBarChart.invalidate();

}

在适配器中:

  Context conext;
  MainActivity mainActivity;

  mainActivity = new MainActivity();

  mainActivity.resetGraph(conext);

如何做到这一点?请帮忙..谢谢..

创建一个实现 Activity 的接口,在您的情况下主要 activity 并覆盖方法并执行操作。

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

在适配器中,您不应创建 MainActivity 的新实例并调用 resetGraph()。您应该使用创建适配器的 MainActivity 实例。将 MainActivity 的实例发送到适配器,new Adapter(this) 并将其保存在适配器中。

您可以像这样从适配器的上下文更改视图: 将上下文转换为 activity。 使用 findviewbyid 方法找到你想要的视图。 将其初始化为一个变量。

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

根据需要更改变量。 笔记。不要忘记使用您想要的视图类型并将 findview 方法转换为它。

如果你想调用一个方法,只需将上下文转换为 MainActivity 并调用它。

在 Adapter 中以这种方式调用你的 resetMethod

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