我有一个名为MoviesActivity的活动,它使用名为MovieAdapter的ListAdapter来显示电影列表。每个列表项具有名称等,以及用户可以单击以播放电影的按钮。我的问题是 - 如何将与按钮关联的onClick代码从MovieAdapter类转移到MoviesActivity类?
public class MoviesActivity extends Activity{
private static final String TAG = "MoviesActivity";
public ListView listView;
public MovieAdapter movieAdapter;
...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movies);
listView = (ListView) findViewById(R.id.MovieListView);
moviesManager = new MoviesManager(client);
List<Movie> allMoviesList = moviesManager.getAllMoviesList();
movieAdapter = new MovieAdapter((Context)this, allMoviesList,moviesManager);
listView.setAdapter(movieAdapter);
}
MovieAdapter的代码
public class MovieAdapter extends BaseAdapter implements OnClickListener{
@Override
public View getView(int position, View convertView, ViewGroup parent) {
...
}
@Override
public void onClick(View v) {
//Play movie
...
}
}
我的MovieAdapter功能齐全。我的问题是 - 我想编写代码来在MoviesActivity中播放电影,而不是在MovieAdaptor中播放。我怎样才能做到这一点?我曾多次遇到过类似的问题,但从未找到过一种好的技术(除了使用静态方法等)。当我尝试在onClick中发出一个getWindow()时问题就出现了 - 因为它不在一个Activity子类中。
答案 0 :(得分:1)
不是将Context
对象传递到MovieAdapter
构造函数中,而是传递MovieActivity
对象并从按钮中运行MovieActivity
的{{1}}方法playMovie(Movie)
事件:
您的活动:
OnClick
您的适配器:
public class MoviesActivity extends Activity {
public ListView listView;
public MovieAdapter movieAdapter;
//...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movies);
listView = (ListView) findViewById(R.id.MovieListView);
moviesManager = new MoviesManager(client);
List<Movie> allMoviesList = moviesManager.getAllMoviesList();
movieAdapter = new MovieAdapter(this, allMoviesList, moviesManager);
listView.setAdapter(movieAdapter);
}
public void playMovie(Movie movie) {
// ...
}
}
答案 1 :(得分:0)
如果您可以扩展ListActivity而不是活动,则可以执行以下操作:
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
}