[英]Java/android Interface method automatic parameter passing concept
經過一個半小時的挫折之后,我似乎無法將我的問題說出來,因此無法進行谷歌搜索,因此我轉向stackoverflow來簡單解釋“接口方法參數自動值傳遞概念”。 我不太能說出什么來解釋這個問題,但我會盡力而為。
我知道java interface
是如何工作的,但是當涉及到在android中實現listener
或其他classes
時,我不理解它的使用方式,在該類中,某些值是通過override
方法參數傳遞給您的。 例如,當您在addTextChangedListener
上實現Edittext
,必須override
所有這些方法( onTextChanged
, beforeTextChanged
, afterTextChanged
)。 在這些方法的參數中,該值會自動傳遞給您,該參數值從何而來。 通常,當您override
interface
方法或任何其他方法時,會在參數中傳遞值,但在這里它會以某種方式自動為您完成。 該值會自動傳遞到overridden
方法的參數中,您只需通過聲明var並將其設置為等於param值來檢索它即可。 您將非常欣賞與此概念相關的hello world
示例。
public interface RequestInterface { public void execute(String val); }
RequestInterface helloWorld= new RequestInterface () {
@Override
public void execute(String val) {
Log.i("tag", val);
}
};
private void methodThatWantsToCallAInterface(String valueToPutInside,RequestInterface command){
command.execute(valueToPutInside);
}
@Override
public void onCreate(Bundle savedInstanceState) {
methodThatWantsToCallAInterface("Some string",helloWorld); //logs "Some string"
}
創建一個接口類
public interface SelectedValue { void onSelectedData(String string);
}
在活動類onCreate method()上方的所需位置設置Value
private SelectedValue mCallback;
覆蓋onAttach
public void onAttach(Activity activity) { super.onAttach(activity); try { mCallback = (SelectedValue) activity; } catch (ClassCastException e) { Log.d("MyDialog", "Activity doesn't implement the ISelectedData interface"); }
}
實行
公共類AyrintiliRapor擴展FragmentActivity實現View.OnClickListener
覆蓋接口類的方法
public void onSelectedData(String value) { txt_tarih.setText("Hello"+value)}
/** The internal interface to extend */
public interface HelloInterface{
String displayText(String prefix);
}
/** The internal class that uses the above interface */
public class HelloWorld{
private HelloInterface myInterface;
public void setHelloInterface(HelloInterface hi){
myInterface=hi;
}
public void print(){
System.out.println(hi.displayText("Hello"));
}
}
/** Your main class */
public class myMainClass{
private HelloWorld hw = new HelloWorld();
public void doIt(){
hw.setHelloInterface(new HelloInterface{
String displayText(String prefix){
return prefix+" World!";
}
}
hw.print(); // normally called by screenRedraw, etc.
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.