在Activity中初始化接口

时间:2017-08-28 09:39:01

标签: android android-activity interface

我的界面

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

2 个答案:

答案 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");