我有一个类,其中包含变量"artist"的getter和setter:
类:
public void setArtist(String artist) {
this.artist = artist;
}
public String getArtist() {
return artist;
}
Run Code Online (Sandbox Code Playgroud)
我想从这样的活动中调用setArtist:
活动1:
Playlist.setArtist(someString)
Run Code Online (Sandbox Code Playgroud)
但是eclipse告诉我,我需要将setArtist更改为static.我使用setter的重点是避免使用任何静态引用.我做错了什么,还是有另一种方法可以做到这一点?
它完全取决于您想要对象的位置和时间.你可以这样做:
class Artist implements Serializable{
public static final String EXTRA = "com.your.package.ARTIST_EXTRA";
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Run Code Online (Sandbox Code Playgroud)
活动1:
public void onCreate(Bundle savedInstance){
// ....
Artist artist = new Artist();
artist.setName("Rolf");
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra(Artist.EXTRA, artist);
startActivity(intent);
}
Run Code Online (Sandbox Code Playgroud)
活动2:
然后,您可以在第二个活动中引用您的艺术家:
public void onCreate(Bundle savedInstance){
// ....
Artist artist = (Artist) getIntent().getSerializableExtra(Artist.EXTRA);
Log.d("YourApp", "I have the artist! "+ artist.getName());
}
Run Code Online (Sandbox Code Playgroud)
观察您正在序列化的内容,因为您无法序列化某些对象.
另一种方法是拥有一个扩展Application并在那里保留引用的类,然后你可以从任何Activity上下文中检索它.
| 归档时间: |
|
| 查看次数: |
11335 次 |
| 最近记录: |