Android : How to set button setOnClickListener if the button in a list activity

on Thursday, August 14, 2014


I created a activity that contain a listview and a button



<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="@android:id/list"></ListView>

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add Task"
android:id="@+id/btn"></Button>
</LinearLayout>


In the class, I added a OnClickListener to the button, Then the app cannot be started



public class Test2 extends ListActivity {
String[] list={"1","2","3"};
Button btn;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

btn = (Button) findViewById(R.id.btn);

btn.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {

}
});

setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list));
}
}


If I remove this



btn.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {

}
});


Then the app is completely work, but the button cannot handle event


How to add the listener to the button when the class extends ListActivity?


0 comments:

Post a Comment