簡體   English   中英

Java / android接口方法自動參數傳遞概念

[英]Java/android Interface method automatic parameter passing concept

經過一個半小時的挫折之后,我似乎無法將我的問題說出來,因此無法進行谷歌搜索,因此我轉向stackoverflow來簡單解釋“接口方法參數自動值傳遞概念”。 我不太能說出什么來解釋這個問題,但我會盡力而為。

我知道java interface是如何工作的,但是當涉及到在android中實現listener或其他classes時,我不理解它的使用方式,在該類中,某些值是通過override方法參數傳遞給您的。 例如,當您在addTextChangedListener上實現Edittext ,必須override所有這些方法( onTextChangedbeforeTextChangedafterTextChanged )。 在這些方法的參數中,該值會自動傳遞給您,該參數值從何而來。 通常,當您override interface方法或任何其他方法時,會在參數中傳遞值,但在這里它會以某種方式自動為您完成。 該值會自動傳遞到overridden方法的參數中,您只需通過聲明var並將其設置為等於param值來檢索它即可。 您將非常欣賞與此概念相關的hello world示例。

  1. 用某種方法創建一個接口,該方法除了某些之外。
  2. 創建此接口的實例,該實例將覆蓋該方法並執行某些操作。
  3. 創建一個需要此接口作為參數的方法。
  4. 使用在2.點中創建的參數和如果接口需要一個參數的另一個參數調用此方法。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM