I would like to use findViewById in my method "setTotalSum" which is called from another class. How can I use it although it's a static method?
public SecondaryDisplay(Context outerContext, Display display) {
super(outerContext, display);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_display);
}
public static void setTotalSum (String invoiceTotalSum){
TextView totalPrice = (TextView)findViewById(R.id.invoicePrice);
totalPrice.setText(invoiceTotalSum);
}
CodePudding user response:
findViewById()
is an instance method of the View
which is the parent of Activity
and Fragment
. You can't use instance methods in static methods.
Either you should pass the view as the param (what I would not recommend) or find another way around to do it without static methods.
public static void setTotalSum (View view, String invoiceTotalSum){
TextView totalPrice = (TextView) view.findViewById(R.id.invoicePrice);
totalPrice.setText(invoiceTotalSum);
}
CodePudding user response:
- If two class is in same package then directly call another class static method by class name.
A.java
public class A {
public static some() {
...
}
}
B.java
public class B {
public static someExtra() {
A.some(); //call by class name
A a = new A();
a.some(); //call by refrence also
}
}
but if some is not static method then create object of A class and then call the method.
Ex:-
public class B {
public static someExtra() {
A a = new A();
a.some();
}
}
Note:- If two class is in diffrent package then must include import.