简体   繁体   English

静态方法如何从调用活动中获取上下文?

[英]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 : 我正在使用MPAndroidChart lib绘制图形,并且在使用marketview时遇到一些问题,代码如下:

MainActivity.java 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 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 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. 我不知道如何在类Chartline中获取上下文 ,因为该方法是静态的。 All the code is copy from the example in the lib, but i am trying to separate the linechart class, and face this problem. 所有代码都是从lib中的示例复制而来的,但是我试图分离linechart类,并面对这个问题。

Basically there are several types of context. 基本上有几种类型的上下文。 In your case you can get it from v.getContext(); 您可以从v.getContext();获取它v.getContext();

Modify HelloME.java like below:- 修改HelloME.java如下:

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 现在在Chartline.java中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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