Cannot find TextView in PreferenceActivity

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-10 11:02:05

问题


In my PreferenceActivity I have some Preferences. One I inflate from layout:

public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   addPreferencesFromResource(R.layout.settings);
   ...
}

protected void onResume() {     
    super.onResume();
    Preference registrationStatus = (Preference) findPreference("registrationStatusPref");
    if (!TextUtils.isEmpty(somestring){
       registrationStatus.setLayoutResource(R.layout.push_reg_status);
       TextView push_reg_status_txt = (TextView)findViewById(R.id.pushRegTxtPref);
    }
    ....
}

push_reg_status_txt is a TextView from push_reg_status layout, and push_reg_status_txt is always null.

push_reg_status layout:

....
<TextView
        android:id="@+id/pushRegTxtPref"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="2dp"
        android:layout_marginBottom="4dp"
        android:text="Registration Succesful"
        android:textColor="#99ff33"
        android:gravity="center_horizontal"
        android:layout_gravity="center_horizontal"/>
.....

Why?


回答1:


Preference.setLayoutResource() only updates the internal reference that preference has to a layout ID, it does not actually update the layout to redisplay. Therefore the TextView you are looking for with findViewById() is not inflated for your use. The only place Preferences inflate their layouts is when created.

You'll either need to have that custom layout set at the start (before addPreferencesFromResource() inflates everything), or adjust the title/summary properties of the existing preference instead to set your "Registration Successful" string. Also, if you are using a custom preference layout, make sure you're following the rules set forth in the SDK Documentation.

Hope that Helps!




回答2:


Maybe because you calls findViewById of your Activity instead of calling same method of registrationStatus object.



来源:https://stackoverflow.com/questions/5702911/cannot-find-textview-in-preferenceactivity

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