简体   繁体   中英

How a static method get context from the calling activity?

I am using MPAndroidChart lib to plot graph, and i got some problem in using with the marketview the code are below :

MainActivity.java

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



    View p = findViewById(R.id.pie);
    ChartPie.Plot(p, p.getId());


    View l = findViewById(R.id.line);
    ChartLine.Plot(l, l.getId());

}

Chartline.java

protected Context context;


public static void Plot(View v, int id){

    LineChart lineChart = v.findViewById(id);

    HelloME mv = new HelloME(**context**, R.layout.mymarketview);
    mv.setChartView(lineChart);
    lineChart.setMarker(mv);

    XAxis xAxis = lineChart.getXAxis();
    xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
                    ...

HelloME.java

    private TextView tvContent;

    public HelloME(Context context, int layoutResource) {
        super(context, layoutResource);

        tvContent = (TextView) findViewById(R.id.hello);
    }

I dont know how to get the context in the class Chartline, because the method is in static. All the code is copy from the example in the lib, but i am trying to separate the linechart class, and face this problem.

Basically there are several types of context. In your case you can get it from v.getContext();

Modify HelloME.java like below:-

private TextView tvContent;
private static Context context_; 

  public HelloME(Context context, int layoutResource) {
    super(context, layoutResource);
    context_ = context;
    tvContent = (TextView) findViewById(R.id.hello);
}
public static Context getContext(){
    return context_;
}

Now in Chartline.java

 HelloME mv = new HelloME(HelloME.getContext(), R.layout.mymarketview);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM