How to call click event on Android ListView Header?
I created a list view and I added a header to it (by using addHeaderview(layout)), then I wrote a click event like:
LayoutInflater inflater = (LayoutInflater)get开发者_C百科SystemService(LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.buypwr, null);
itemView.setOnClickListner(new OnClickListner(){
@Override
public void onClick(View v){
}
But this onClick event didn't fire when I clicked on the header, so can anyone tell me how can I solve my problem?
just try this..
itemView.setOnClickListner(new View.OnClickListner()
{
@Override
public void onClick(View v)
{
}
}
If you have TextView in buypwr.xml then try this
TextView txt = (TextView)itemView.findViewById(......);
txt.setOnClickListner(new View.OnClickListner()
{
@Override
public void onClick(View v)
{
}
}
If you want clickable Header as basic list item. Inflate it with ListView.
LayoutInflater inflater = LayoutInflater.from(mContext)
mListView.addHeaderView(inflater.inflate(R.layout.list_item_header, mListView, false));
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//parent.getItemAtPosition(position)
//Prepare to get it at position == 0
}
});
What worked for me:
When inflating the header view, before adding it to the listview, I then used that view to get the subview and add a click listener on it
myHeaderView.findViewById(R.id.myButton).setOnClickListener(new OnClickListener() { ... } );
also, when I added it to the listView, I used the overloaded constructor with the third variable set to true
mListView.addHeaderView(myHeaderView, null, true);
use setOnItemClickListener to set the click event for the list and implement a customized OnItemClickListener for your own use.
android.widget.AdapterView.setOnItemClickListener(OnItemClickListener listener)
If you do not have any specific widgets (buttons etc) which can have listener, you can get your header by calling onItemClickListener() as @Nicoloas said at position 0 as its the first item. You can even set a specific id for you header view and access it in onItemClickListener() by calling view.getId(). Let me know if otherwise.
精彩评论