【问题标题】:ListPreference that contains dynamic data from MainActivity包含来自 MainActivity 的动态数据的 ListPreference
【发布时间】:2018-02-08 18:18:26
【问题描述】:

我正在尝试创建一个ListPreference,以显示成功连接的 IP 地址列表。

我在MainActivity 中将 IP 地址标记为已成功连接,我希望有一种方法可以将成功的 IP 地址作为数组附加到 SharedPreferences,这样当用户打开 PreferencesActivity ,有一个ListPreference 显示我标记为成功的IP 地址。

我已经看过this 的帖子,它真的很接近,但我认为我不能将SharedPreference 字符串集转换为CharSequence[] 可以吗?

到目前为止,这是我的代码:

public class IPHistoryListPreference extends ListPreference {

   SharedPreferences sharedPref;

   public IPHistoryListPreference(Context context, AttributeSet attrs) {
       super(context, attrs);
       sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
   }

   public IPHistoryListPreference(Context context) {
       super(context);
       sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
   }

   @Override
   protected View onCreateDialogView() {
       ListView view = new ListView(getContext());
       view.setAdapter(adapter());
   }

   private ListAdapter adapter() {
       return new ArrayAdapter(getContext(), android.R.layout.select_dialog_singlechoice);
   }

   private CharSequence[] entries() {
    //convert sharedPref stringSet to CharSequence[] ?
   }

   private CharSequence[] entryValues() {
    //convert sharedPref stringSet to CharSequence[] ?
   }

}

【问题讨论】:

    标签: java android


    【解决方案1】:

    您可以将您的响应通过管道传输到一个字符串中,然后拆分为一个数组以获取每个 IP 地址。

    Eg string IPS = "some IP address|some IP address......
    

    【讨论】:

      【解决方案2】:

      我用一些 hacky 解决方案解决了这个问题。

      首先是将Set<String> 转换为CharSequence[]

      Set<String> stringSet = sharedPref.getStringSet("IPEntries", null);
          return stringSet.toArray(new CharSequence[stringSet.size()]);
      

      然后为了提​​取我的 MainActivity 中的集合,我只使用了这段代码:

      Set<String> set = sharedPref.getStringSet("IPEntries", null);
      if (set == null) {
                      set = new HashSet<>();
                      set.add(ipAddressName);
                  }
                  if (!set.contains(ipAddressName)) {
                      set.add(ipAddressName);
                  }
                  sharedPref.edit().putStringSet("IPEntries", set).apply();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-29
        相关资源
        最近更新 更多