2017-08-28 144 views
-10

我的接口初始化接口

public interface Baseface { 

    public void updatedName(String newName); 
} 

MainActivity

public class MainActivity extends AppCompatActivity { 

private Baseface baseface; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    baseface = (Baseface) this; 
    baseface.updatedName("hello"); 

    Intent i = new Intent(MainActivity.this, SecondActivity.class); 
    startActivity(i); 
    } 

}

SecondActivity

public class SecondActivity extends AppCompatActivity implements Baseface { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_second); 

} 

@Override 
public void updatedName(String newName) { 
    Log.e("my new name is:",newName); 
} 

}

我有錯誤

Caused by: java.lang.ClassCastException. MainActivity cannot be cast to Baseface 
+0

研究以及有關的接口。 –

+0

https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – larsgrefer

+3

使用接口進行活動間通信是一種錯誤的方法。 – Selvin

回答

3

MainActivity必須實現Baseface爲投給sucess。

public class MainActivity extends AppCompatActivity implements Baseface 
    ... 
0

試試這個讓你MainActivity工具Baseface所以MainActivity是可以轉換爲Baseface

這樣

public class MainActivity extends AppCompatActivity implements Baseface { 
    private Baseface baseface; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    baseface = (Baseface) this; 
    baseface.updatedName("hello"); 

    Intent i = new Intent(MainActivity.this, SecondActivity.class); 
    startActivity(i); 
    } 

} 

,如果你想從以上的活動等傳遞數據您可以通過以下代碼intent代碼

發送數據使用putExtra()法這樣從您的主要活動

Intent i = new Intent(MainActivity.this, SecondActivity.class); 
i.putExtra("data", "hello"); 
startActivity(i); 

intent現在你SecondActivity收到這樣

Intent intent = getIntent(); 
String data = intent.getStringExtra("data");