我正在尝试从 SharedPreferences 对象创建一个键列表。由于用户可以添加新的键值对,我需要动态地进行。
这是我活动的 onCreate 函数:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater inflater = this.getLayoutInflater();
LinearLayout layout = (LinearLayout)inflater.inflate(R.layout.activity_show_saved, null);
this.add_here = (LinearLayout)layout.findViewById(R.id.saved_list);
// Loading shared preferences
SharedPreferences sp = this.getSharedPreferences("saved_sequences", MODE_PRIVATE);
Map<String, ?> kv = sp.getAll();
int i = 0;
// Iterating through shared preferences
for(Map.Entry<String, ?> entry : kv.entrySet()) {
Toast.makeText(this, entry.getKey(), Toast.LENGTH_SHORT).show();
TextView to_add = new TextView(this);
to_add.setText(entry.getKey());
to_add.setId(i++);
this.add_here.addView(to_add, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
}
this.setContentView(layout);
}
this.add_here
声明为的类变量在哪里private LinearLayout
。这是正在膨胀的 xml 文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/background"
tools:context=".ShowSaved" >
<com.google.ads.AdView
android:id="@+id/adViewTop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adUnitId="*****************"
ads:adSize="SMART_BANNER"
ads:testDevices="TEST_EMULATOR"
ads:loadAdOnCreate="true" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="@+id/saved_list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
</LinearLayout>
不幸的是,我得到一个空白屏幕。问题在于添加 TextViews,因为 while 内的 Toast 正确地显示了已保存的键,正如预期的那样。