最新消息:20210917 已从crifan.com换到crifan.org

【已解决】rcsjta项目编译出错:警告 deprecation PreferenceActivity中的addPreferencesFromResource(int)已过时

出错 crifan 787浏览 0评论
折腾:
【未解决】Android Studio中gradle编译rcjsta项目多个使用或覆盖了已过时的API等报错
期间,继续解决其他错误:
rcsjta/samples/api/tts/src/com/orangelabs/rcs/tts/Main.java:62: 警告: [deprecation] PreferenceActivity中的addPreferencesFromResource(int)已过时
        addPreferencesFromResource(R.xml.tts_preferences);
        ^
代码是:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    askPermissions();
    // Set title
    setTitle(R.string.app_title);


    // Set preferences
    addPreferencesFromResource(R.xml.tts_preferences);
    activateCheck = (CheckBoxPreference) getPreferenceScreen().findPreference("activate");
    activateCheck.setOnPreferenceChangeListener(this);
}
中的:
addPreferencesFromResource(R.xml.tts_preferences);
去看定义
android/preference/PreferenceActivity.java
/**
 * Inflates the given XML resource and adds the preference hierarchy to the current
 * preference hierarchy.
 *
 * @param preferencesResId The XML resource ID to inflate.
 *
 * @deprecated This function is not relevant for a modern fragment-based
 * PreferenceActivity.
 */
@Deprecated
public void addPreferencesFromResource(int preferencesResId) {
    requirePreferenceManager();


    setPreferenceScreen(mPreferenceManager.inflateFromResource(this, preferencesResId,
            getPreferenceScreen()));
}
果然标记了已废弃
deprecation PreferenceActivity中的addPreferencesFromResource int
有关PreferenceActivity的Android弃用方法警告 – Thinbug
https://www.thinbug.com/q/14756457
sharedpreferences – Android- deprecated method warning regarding PreferenceActivity – Stack Overflow
解释了,之所以描述中没给出替换的备用方法,是因为整个思路变了:
推荐换用
PreferenceFragment  |  Android 开发者  |  Android Developers
-》不过此时 20200807此页面,也提示了:
This class was deprecated in API level 28.
API=28时,又会废弃此,对于之前来说新的方式
建议:
Use the AndroidX Preference Library for consistent behavior across all devices. For more information on using the AndroidX Preference Library see Settings.
相关内容:
AndroidX 概览  |  Android 开发者  |  Android Developers
”在项目中使用 androidx 库
如需了解如何迁移现有项目,请参阅迁移到 AndroidX。
如果要在新项目中使用命名空间为 androidx 的库,则需要将编译 SDK 设置为 Android 9.0(API 级别 28)或更高版本,并在 gradle.properties 文件中将以下两个 Android Gradle 插件标记设置为 true。
* android.useAndroidX:该标记设置为 true 时,Android 插件会使用对应的 AndroidX 库,而非支持库。如果未指定,则该标记默认为 false。
* android.enableJetifier:该标记设置为 true 时,Android 插件会通过重写其二进制文件来自动迁移现有的第三方库,以使用 AndroidX 依赖项。如果未指定,该标记默认为 false。”
->不过,此处不想这么轻易改动api的版本=sdk的版本
因为影响估计会很大
会导致其他代码,可能都要修改
项目不是自己写的,且代码量很大,所以不能轻易改
androidx.preference  |  Android 开发者  |  Android Developers
https://developer.android.com/reference/androidx/preference/package-summary
设置  |  Android 开发者  |  Android Developers
PreferenceActivity已废弃,但是现在可以用PreferenceFragment
和:PreferenceFragmentCompat
android – What to use instead of “addPreferencesFromResource” in a PreferenceActivity? – Stack Overflow
点赞最多的也是和前面说的一样
建议用
PreferenceActivity  |  Android 开发者  |  Android Developers
而此时20200806,此页面也提示:
This class was deprecated in API level 29.
Use the AndroidX Preference Library for consistent behavior across all devices. For more information on using the AndroidX Preference Library see Settings.
不过感觉,还是可以暂时用用的。
android – Was PreferenceFragment intentionally excluded from the compatibility package? – Stack Overflow
android 3.0+建议用:PreferenceFragment
参考代码
cw-android/Prefs/FragmentsBC at master · commonsguy/cw-android
但是都是9年前的,放弃。
cw-omnibus/Prefs/FragmentsBC at master · commonsguy/cw-omnibus
有最新几年的代码,还算值得参考
android – Alternative to addPreferencesFromResource as its deprecated – Stack Overflow
PreferenceActivity已废弃,其中的addPreferencesFromResource() 也就没了
现在建议是:
PreferenceFragment + PreferenceActivity
PreferenceActivity  |  Android 开发者  |  Android Developers
那现在问题就变成:
如何把之前的:
addPreferencesFromResource(R.xml.tts_preferences);
以及另外一个相关的getPreferenceScreen:
// Set preferences
addPreferencesFromResource(R.xml.tts_preferences);
activateCheck = (CheckBoxPreference) getPreferenceScreen().findPreference("activate");
改为最新的api的代码
PreferenceActivity  |  Android 开发者  |  Android Developers
https://developer.android.com/reference/android/preference/PreferenceActivity
addPreferencesFromResource(int preferencesResId)
This method was deprecated in API level 15. This function is not relevant for a modern fragment-based PreferenceActivity.
Inflates the given XML resource and adds the preference hierarchy to the current preference hierarchy.
api=15后就废弃了。
去参考代码
compatibility – How could I use the same set of preference screens for all Android versions from 2.X to 4.X? – Stack Overflow
import android.annotation.TargetApi;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceScreen;


public class CompatiblePreferenceActivity extends PreferenceActivity
{
    private int prefs=0;


    //Get/Set
    public void setPrefs(int prefs)
    {
        this.prefs=prefs;
    }


    //Exception
    protected static class PrefsNotSetException extends RuntimeException
    {
        private static final long serialVersionUID = 1L;
        PrefsNotSetException()
        {
            super("\"prefs\" should be set to a valid preference resource ID.");
        }
    }


    //Creation
    @Override
    protected void onCreate(final Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        if (prefs==0)
            throw new PrefsNotSetException();
        else
            try {
                getClass().getMethod("getFragmentManager");
                AddResourceApi11AndGreater();
                }
            catch (NoSuchMethodException e) { //Api < 11
                    AddResourceApiLessThan11();
                }
    }


    @SuppressWarnings("deprecation")
    protected void AddResourceApiLessThan11()
    {
        addPreferencesFromResource(prefs);
    }


    @TargetApi(11)
    protected void AddResourceApi11AndGreater()
    {
        PF.prefs=prefs;
        getFragmentManager().beginTransaction().replace(
            android.R.id.content, new PF()).commit();
    }


    @TargetApi(11)
    public static class PF extends PreferenceFragment
    {
        private static int prefs;
        @Override
        public void onCreate(final Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(prefs);
        }
    }


    //Sub-screen background glitch fix
    @SuppressWarnings("deprecation")
    @Override
    public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
        Preference preference)
    {
        super.onPreferenceTreeClick(preferenceScreen, preference);
        if (preference!=null)
            if (preference instanceof PreferenceScreen)
                if (((PreferenceScreen)preference).getDialog()!=null)
                    ((PreferenceScreen)preference).getDialog().
                        getWindow().getDecorView().
                        setBackgroundDrawable(this.getWindow().
                            getDecorView().getBackground().getConstantState().
                            newDrawable());
        return false;
    }
}
去试试
不过有点不懂
再去下载参考代码
https://github.com/commonsguy/cw-omnibus/tree/master/Prefs/FragmentsBC
另外去代码中找找tts_preferences
找到了:
samples/api/tts/res/xml/tts_preferences.xml
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">


    <CheckBoxPreference
        android:key="activate"
        android:title="@string/label_activate"
        android:summaryOn="@string/label_summary_activate_on"
        android:summaryOff="@string/label_summary_activate_off"/>
    
</PreferenceScreen>
另外android studio中没搜到
但是可以通过双击进去界面中
然后右键Go to XML 进入xml
rcsjta/samples/api/tts/res/xml/tts_preferences.xml
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">


   <CheckBoxPreference
      android:key="activate"
      android:title="@string/label_activate"
      android:summaryOn="@string/label_summary_activate_on"
      android:summaryOff="@string/label_summary_activate_off"/>
    
</PreferenceScreen>
然后注意到了,右上角有3种方式:
Code Split Design
点击了可以看到属性
去看了参考代码
/Users/xxx/dev/src/android/cw-omnibus/Prefs/FragmentsBC/app/src/main/java/com/commonsware/android/preffragsbc/EditPreferences.java
package com.commonsware.android.preffragsbc;


import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import java.util.List;


public class EditPreferences extends PreferenceActivity {
  @Override
  public void onBuildHeaders(List<Header> target) {
    loadHeadersFromResource(R.xml.preference_headers, target);
  }


  @Override
  protected boolean isValidFragment(String fragmentName) {
    if (First.class.getName().equals(fragmentName)
        || Second.class.getName().equals(fragmentName)) {
      return(true);
    }


    return(false);
  }


  public static class First extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);


      addPreferencesFromResource(R.xml.preferences);
    }
  }


  public static class Second extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);


      addPreferencesFromResource(R.xml.preferences2);
    }
  }
}
/Users/xxx/dev/src/android/cw-omnibus/Prefs/FragmentsBC/app/src/main/java/com/commonsware/android/preffragsbc/FragmentsDemo.java
package com.commonsware.android.preffragsbc;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;


public class FragmentsDemo extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
  }


  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.actions, menu);


    return(super.onCreateOptionsMenu(menu));
  }


  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.settings:
        startActivity(new Intent(this, EditPreferences.class));


        return(true);
    }


    return(super.onOptionsItemSelected(item));
  }
}

/Users/xxx/dev/src/android/cw-omnibus/Prefs/FragmentsBC/app/src/main/java/com/commonsware/android/preffragsbc/PreferenceContentsFragment.java
package com.commonsware.android.preffragsbc;


import android.app.Fragment;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


public class PreferenceContentsFragment extends Fragment {
  private TextView checkbox=null;
  private TextView ringtone=null;
  private TextView checkbox2=null;
  private TextView text=null;
  private TextView list=null;


  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup parent,
                           Bundle savedInstanceState) {
    View result=inflater.inflate(R.layout.content, parent, false);


    checkbox=(TextView)result.findViewById(R.id.checkbox);
    ringtone=(TextView)result.findViewById(R.id.ringtone);
    checkbox2=(TextView)result.findViewById(R.id.checkbox2);
    text=(TextView)result.findViewById(R.id.text);
    list=(TextView)result.findViewById(R.id.list);


    return(result);
  }


  @Override
  public void onResume() {
    super.onResume();


    SharedPreferences prefs=
        PreferenceManager.getDefaultSharedPreferences(getActivity());


    checkbox.setText(Boolean.valueOf(prefs.getBoolean("checkbox", false)).toString());
    ringtone.setText(prefs.getString("ringtone", "<unset>"));
    checkbox2.setText(Boolean.valueOf(prefs.getBoolean("checkbox2", false)).toString());
    text.setText(prefs.getString("text", "<unset>"));
    list.setText(prefs.getString("list", "<unset>"));
  }
}
但还是看不太懂。
目前感觉还是有点复杂。
暂时不去继续花精力解决此问题。后续需要再去继续。

后记:
好像
android – What to use instead of “addPreferencesFromResource” in a PreferenceActivity? – Stack Overflow
有简单的实现供参考?
去试试
结果此处:
//        addPreferencesFromResource(R.xml.tts_preferences);


        public static class MyPreferenceFragment extends PreferenceFragment
        {
            @Override
            public void onCreate(final Bundle savedInstanceState)
            {
                super.onCreate(savedInstanceState);
                addPreferencesFromResource(R.xml.tts_preferences);
            }
        }
        getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
却始终报错
public static class MyPreferenceFragment extends PreferenceFragment
提示:
Modifier static not allowed here
然后:
public class MyPreferenceFragment extends PreferenceFragment
但是又提示:
Modifier 'public' not allowed here
去掉变成:
class MyPreferenceFragment extends PreferenceFragment
又提示:
This fragment class should be public (null) 
所以不知道如何改了。
后来放到函数外部:
    public static class MyPreferenceFragment extends PreferenceFragment
    {
        @Override
        public void onCreate(final Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.tts_preferences);
        }
    }

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

        askPermissions();
        // Set title
        setTitle(R.string.app_title);

        // Set preferences
//        addPreferencesFromResource(R.xml.tts_preferences);

        getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
至少没有报错了。
重新编译后,错误消失了。
【总结】
之前代码:
public class Main extends PreferenceActivity implements Preference.OnPreferenceChangeListener {
。。。
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
。。。
        // Set preferences
        addPreferencesFromResource(R.xml.tts_preferences);
。。。
报错:
告: [deprecation] PreferenceActivity中的addPreferencesFromResource(int)已过时
        addPreferencesFromResource(R.xml.tts_preferences);
        ^
原因:addPreferencesFromResource已废弃
解决办法:
换成新的PreferenceFragment+PreferenceActivity的写法
public class Main extends PreferenceActivity implements Preference.OnPreferenceChangeListener {

    public static class MyPreferenceFragment extends PreferenceFragment
    {
        @Override
        public void onCreate(final Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.tts_preferences);
        }
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
。。。
        // Set preferences
//        addPreferencesFromResource(R.xml.tts_preferences);
        getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
。。。
    }
即可。

转载请注明:在路上 » 【已解决】rcsjta项目编译出错:警告 deprecation PreferenceActivity中的addPreferencesFromResource(int)已过时

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
87 queries in 0.185 seconds, using 20.11MB memory