【Android】ListView的點擊事件的實現

不是什麼特別難的複雜的代碼,日常「度娘」給出的答案卻也不是那麼的盡人意java

今天又趕上了,因此本身總結一下吧 ide

  • 無圖無真相
    post

========Activity========this

【List 1】點擊跳轉到百度
code

-----------------------------------
接口

【List 2】點擊跳轉到Googleci

-----------------------------------
get

【List 3】點擊跳轉到微軟it

-----------------------------------
io

【List 4】點擊跳轉到阿里巴巴

... ...

... ...

========Activity========

  • 功能點

點擊對應的item發起對應的跳轉動做


  • 乾貨

    Activity端

public class CircleMsgAcitvity extends BaseActivity 
    //【1】包含接口
    implements OnItemClickListener {
    ... ...
    ... ...

    //【2】實現接口
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long arg3) {
        // 從Adapter中得到點擊條目中數據源包含的帖子id
        //★★★從Adapter中得到被點擊的item的數據實體,並取出來賦值給postId 
        String postId = msgAdapter.getItem(position).getPostId();
        // 根據postId啓動對應的【帖子詳情】
        switch2DetailView(postId);
    }


    //【3】想要的動做:根據postId進行跳轉
    //postId能夠是{百度地址,Google地址...}
    private void switch2DetailView(String postId) {
        Intent intent = new Intent(this, CircleActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("postId", postId);
        intent.putExtras(bundle);
        startActivity(intent);
    }
    
    //【4】接口綁定
    private void initView() {
        bkBtn = (Button) findViewById(R.id.btn_back);
        bkBtn.setOnClickListener(this);
        // 綁定數據源
        msgList = (MyListView) findViewById(R.id.circle_msg_list);
        msgAdapter = new CircleMsgAdapter(this);
        msgList.setAdapter(msgAdapter);
        //接口綁定
        msgList.setOnItemClickListener(this);
    }

}

    

    Adapter端

public class CircleMsgAdapter extends BaseAdapter {
... ...
... ...
    //【5】搭一個橋:讓Activity能夠取到Adapter中被點擊item中的數據實體
    @Override
    //public Object getItem(int position) {
    //★★★ 關鍵的一步,修改BaseAdapter中getItem返回的類型
    //【Object】---》【CircleMsgItemInfo 】
    public CircleMsgItemInfo getItem(int position) {
        return mInfos.get(position);
    }

... ...
... ...

}
相關文章
相關標籤/搜索