1

I am trying to define a class like so, so I can have it show up in XML:

public class MyLineChart extends com.github.mikephil.charting.charts.LineChart {
    private Context mContext;

    public MyLineChart(Context context) {
        super(context);
        mContext = context;
    }

    public MyLineChart(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
    }

    public LineChart(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContext = context;
    }

    // ...
}

So when I am defining this object I am doing:

mChart = (MyLineChart) findViewById(R.id.line_chart);

But what if I'd like to send in other arguments through the constructors? For example say the MyLineChart class had another field:

private int mSomeInt;

and I'd like to be able to set mSomeInt through the constructor so I am not just setting mContext to context but also mSomeInt to some integer I pass in. I'm using the integer as an example but it could technically be any argument.

Can this be done?

  • check this http://stackoverflow.com/questions/37071725/pass-data-from-activity-to-fragment-class-cast-exception/37072002#37072002 – Sreehari May 07 '16 at 20:17

1 Answers1

1

So when I am defining this object I am doing:

mChart = (MyLineChart) findViewById(R.id.line_chart);

Here, although you are assigning the mChart variable, you're not creating a MyLineChart object, you're just assigning an already created object to mChart.

If defined in some xml file (like I think you have done), then your class will be created by Android, using the following constructor:

public MyLineChart(Context context, AttributeSet attrs) {
...
}

You could pass in attributes from xml, where you would parse attrs to extract their values. See this guide on how to use custom attributes with your view if you're trying to pass in constant values, such as a colour for the view, or some default value.

If instead, you want to set some value that you only know at runtime, you can either:

  1. Use a setter

    I recommend this approach. Just add a method to MyLineChart like

    void setMyValue(int myValue) {
      mMyValue = myValue;
      //notify parts of the view that this property has changed
      ...
    }
    
  2. Create the object programatically.

    Here you don't include the view in xml, and instead create it programatically be replacing

    mChart = (MyLineChart) findViewById(R.id.line_chart);
    

    with

    mChart = new MyLineChart(context, myValue);
    //code that adds the view to the layout like a LinearLayout etc.
    ...
    

    For this to work you would create a new constructor for MyLineChart, something like

    public MyLineChart(Context context, int myValue) {
      super(context);
      mContext = context;
      mMyValue = myValue;
    }
    
roarster
  • 4,058
  • 2
  • 25
  • 38