【问题标题】:How to refresh a view in main activity from an adapter?如何从适配器刷新主要活动中的视图?
【发布时间】:2016-08-27 04:54:34
【问题描述】:

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

当我选中复选框或删除任何项目时,我想重置主要活动图表。

为此,我在主要活动中创建了一种方法。并在适配器 onCheckedChangeListener 和单击删除时调用此方法。

但我在 mBarChart 上遇到空指针异常。 IE 。图形。我在 setUI 方法中的 mBarChart 中进行了实例化,这在活动的 onCreate 中被调用。

重置方法

    public void resetGraph(Context context)
{

    mBarChart.invalidate();

}

在适配器中:

  Context conext;
  MainActivity mainActivity;

  mainActivity = new MainActivity();

  mainActivity.resetGraph(conext);

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

【问题讨论】:

  • notifyDataSetChanged怎么样
  • 我应该如何以及在哪里打电话? @千里眼
  • 您要刷新适配器的数据吗?
  • 我想刷新条形图的数据。 @NarenderNishad
  • 简单使用notifiydatasetchange

标签: android android-activity view refresh adapter


【解决方案1】:

在 Adapter 中这样调用你的 resetMethod

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

【讨论】:

  • 这给了我一个类转换异常。
【解决方案2】:

在您的案例中创建一个实现 Activity、Main 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();
}

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      您可以从适配器的上下文中更改视图,如下所示: 将上下文转换为活动。 使用 findviewbyid 方法找到你想要的视图。 将其初始化为一个变量。

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-28
        • 2020-07-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多