Textview单击列表视图

时间:2014-05-07 15:21:57

标签: android listview textview

我在listview中有一个textview,点击它应该执行一些活动。目前,我正在自定义适配器类的getView方法中编写onview of textview。单击textview,我在Activity类中触发了一个方法。但是,当Activity已经在onCreate of Activity中初始化时,该Activity将该变量值设置为NULL。这是我的代码:

适配器类:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
     final int pos = position;
        Item item = (Item) getItem(position);
        TextView textView = (TextView) view
                .findViewById(R.id.tv_song_title);
        textView.setText(item.text);

        textView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                  MainActivity main = new MainActivity();
                main.songPicked(pos); //calling act class method
            }
        });

活动类:

    private MusicService musicSrv;
    public void songPicked(int position) {  //method called
    if (musicSrv!=null) //is null .Why??
    {
    musicSrv.setSong(position);
    songName = musicSrv.playSong();

    }
}

   @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
            songAdt = new SongAdapter();
    songAdt.setRows(rows);
    songView.setAdapter(songAdt);
    playMusic();
        }
    public void playMusic() {

    if (playIntent == null) {
        playIntent = new Intent(this, MusicService.class);
        startService(playIntent);
        bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);

    }

}
  // connect to the service
private ServiceConnection musicConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        MusicBinder binder = (MusicBinder) service;
        // get service
        musicSrv = binder.getService();
        // pass list
        musicSrv.setList(songList);
        musicBound = true;
        Log.i("LEAKTEST", "Connected to instance " + this.toString());

    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

        musicBound = false;
        musicSrv = null;

    }

1 个答案:

答案 0 :(得分:0)

使用listeners代替传递整个活动。

主要想法是

public interface SmthListener() {
    void onSmthHappens(smthParams);
}

public class WhoNotify {
    SmthListener mListener;

    public WhoNotify(SmthListener listener) {
        mListener = listener;
    }

    public void smthHappensInMyClass() {
        mListener.onSmthHappens(smthParams);
    }

}


public class WhoListene implements SmthListener {
    @Override
    public void onCreate(...) {
        ... new WhoNotify(this);
    }

    @Override
    void onSmthHappens(smthParams) {
        // do stuff;
    }
}