Custom Preference - Button not clickable
Solution 1:
onPreferenceClick is triggered when the Prefererence has been clicked not when you click the button. If you want to catch the button click you need to set a OnClickListener on the button itself. The problem is to retrieve the inflated button since the Preference class doesn't have a findViewById method or anything similar. Here's how I'd do it:
- Create a custom Preference class and override the onCreateView
- In the onCreateView method you grab the inflated layout from the super class and find the Button
- Add an OnClickListener to the button
- Use your custom Preference class in your preference layout file
public class CustomPreference extends Preference {
public CustomPreference(Context context) {
super(context);
}
public CustomPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected View onCreateView(ViewGroup parent) {
View preferenceView = super.onCreateView(parent);
setOnClickListener(preferenceView);
return preferenceView;
}
private void setOnClickListener(View preferenceView) {
if (preferenceView != null && preferenceView instanceof ViewGroup) {
ViewGroup widgetFrameView = ((ViewGroup)preferenceView.findViewById(android.R.id.widget_frame));
if (widgetFrameView != null) {
// find the button
Button theButton = null;
int count = widgetFrameView.getChildCount();
for (int i = 0; i < count; i++) {
View view = widgetFrameView.getChildAt(i);
if (view instanceof Button) {
theButton = (Button)view;
break;
}
}
if (theButton != null) {
// set the OnClickListener
theButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// do whatever you want to do
}
});
}
}
}
}
}
This replaces the Preference in your xml file:
<yourpackage.CustomPreference
android:key="your_id"
android:title="@string/your_title"
android:summary="@string/your_summary"/>
Solution 2:
I would use something similar to the code below to implement this:
@Override
protected View onCreateView (ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View customRow = inflater.inflate(R.layout.preferences_station_list_row, null);
((ImageButton) customRow.findViewById(R.id.pref_delete_station)).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//perform whatever you need to button to do here.
}
});
customRow.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showDialog(null);
}
});
customRow.setClickable(true);
return customRow;
}
Has this solved your issue?