Android get view of Preference in PreferenceActivity

北慕城南 提交于 2019-12-19 05:35:32

问题


I would like to get View instance that is used to display specific Preference in my PreferenceActivity, so i can modify its properties, for example:

public class SettingsActivity extends PreferenceActivity {

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

        addPreferencesFromResource(R.xml.preference);
        Preference pref = findPreference("key");
        pref.getView().setVisibility(View.GONE);
            //not necessarily setVisibility, i hope you get my point
    }
}

I only found this method: getView (View convertView, ViewGroup parent). But it seems confusing to me, that if i want to get View of my preference, i need to provide view and viewGroup as parameters??

Could someone explain how to use this method, or point me to another method to get View from my Preference instance.

PS: if possible, i would rather NOT extend Preference class, but i dont mind it if necessary


回答1:


I'm not sure on how to get the view for a preference, but if you want to remove the view from the screen (set visibility to View.gone) you can use the following:

getPreferenceScreen().removePreference(thePreference)




回答2:


To get the view of a desired preference you can use this:

@Override
public void onWindowFocusChanged(boolean hasFocus)
{
    super.onWindowFocusChanged(hasFocus);
    Preference preference=findPreference(“preferenceKey”);
    View preferenceView=getListView().getChildAt(preference.getOrder());
    //Do your stuff
}

Note: You can not do this in the onCreate method because it will throw a NullPointerException.




回答3:


PreferenceActivity inherits the ListActivity class. ListActivity has a method called getListView() which returns the ListView that displays your preferences.

EDIT: Here is the code in my comment formatted:

getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
       // ... put listener code here 
});


来源:https://stackoverflow.com/questions/8432013/android-get-view-of-preference-in-preferenceactivity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!