我的界面
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 :(得分:3)
MainActivity
必须实施Baseface
才能使演员成功。
public class MainActivity extends AppCompatActivity implements Baseface
...
答案 1 :(得分: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
使用intent
使用putExtra()
这样的方法从您的主要活动
Intent i = new Intent(MainActivity.this, SecondActivity.class);
i.putExtra("data", "hello");
startActivity(i);
现在收到SecondActivity
这样的
Intent intent = getIntent();
String data = intent.getStringExtra("data");