我試圖從SharedPreferences對象創建密鑰列表。由於用戶可以添加新的鍵值對,所以我需要動態地執行它。將TextView添加到採用SharedPreferences密鑰的文本的LinearLayout中
這裏是我活動的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,因爲Toast內部正確地顯示了保存的鍵,因爲它預期會做。
問:爲什麼不使用ListView? – Eric
您要導入哪些LayoutParams類? – Sam
@Sam,我正在導入'android.widget.LinearLayout.LayoutParams'。我會給ListView一個嘗試,但我想明白爲什麼這不起作用。 – Zagorax