I wrote a testing app which dynamically add preference (support.v7), but the added preference does not have focus. However, dynamically added preference (v1) can have focus.
For example: (support.v7 example, no focus)
import android.support.v14.preference.PreferenceFragment;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceScreen;
public final class MySettings extends PreferenceFragment {
private IntentFilter mIntentFilter;
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals("android.intent.action.MYTEST")) {
Preference pref1 = new Preference(getPreferenceManager().getContext());
pref1.setTitle("First");
getPreferenceScreen().addPreference(pref1);
}
}
};
@Override
public void onResume() {
super.onResume();
addPreferencesFromResource(R.xml.my_settings); // only contains a PreferenceScreen
mIntentFilter = new IntentFilter("android.intent.action.MYTEST");
getActivity().registerReceiver(mReceiver, mIntentFilter);
}
}
However, the following can have focus (v1 example, have focus)
import android.preference.PreferenceFragment;
import android.preference.Preference;
import android.preference.PreferenceScreen;
public final class MySettings extends PreferenceFragment {
private IntentFilter mIntentFilter;
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals("android.intent.action.MYTEST")) {
Preference pref1 = new Preference(getContext());
pref1.setTitle("First");
getPreferenceScreen().addPreference(pref1);
}
}
};
@Override
public void onResume() {
super.onResume();
addPreferencesFromResource(R.xml.my_settings); // only contains a PreferenceScreen
mIntentFilter = new IntentFilter("android.intent.action.MYTEST");
getActivity().registerReceiver(mReceiver, mIntentFilter);
}
}
But I need to use supporting library v7 due to porting task. How can I have focus using supporting library v7?
Thanks.
In the
onResume
of yourPreferenceFragment
orPreferenceFragmentCompat
, set a focus on the listview used to show the preferences:more info here :