在我的应用程序中,我创建了大约3个收藏夹联系人,可以从设备的现有联系人中进行选择。我能够使用名称和电话号码成功地将FAV联系人存储到SharedPreferences上,并且还能够检索该信息并将其显示在TextView中。但是我想要的是在那之后以custom_row布局在列表视图中显示该数据。(我已经使用了TextView的东西来确保我可以正确地检索它-对我自己来说是一个小测试)
我需要帮助的地方是“在从SharedPreferences中检索的ListView中显示FAV联系人数据”。我在显示代码的地方可以在TextView中显示数据。如果您能建议我如何将其放在ListView上,我将感到非常高兴。
以下是代码段:
public class FavContacts_Activity extends ActionBarActivity {
TextView title, tV_Contacts_list;
Button go_Back_to_ContactsList;
ListView imp_Contacts_List;
public static final String PREF_FILE_NAME = "PACKAGE";
SharedPreferences preferences;
String [] imp_Contacts = {};
StringBuffer sb = new StringBuffer();
int count = 0, i = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView (R.layout.favcontacts_list);
title = (TextView) findViewById (R.id.contacts_title);
tV_Contacts_list = (TextView) findViewById (R.id.tV_Contacts_list);
imp_Contacts_List = (ListView) findViewById (R.id.listView1);
go_Back_to_ContactsList = (Button) findViewById (R.id.btn_Back);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, imp_Contacts);
preferences = getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
for (count = 0; count <3; count++) {
String contacts_list = preferences.getString("CONTACT "+count, null);
tV_Contacts_list.setTextSize(15);
tV_Contacts_list.append("\n "+ i +". "+ contacts_list);
imp_Contacts_List.setAdapter(adapter);
i++;
}
go_Back_to_ContactsList.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}
}
让我知道是否需要其他代码部分,以便通过AlertDialogs将FAV联系人存储到SharedPreferences上。
下面是屏幕快照:
我不知道为什么要在循环中设置适配器,但这是一个示例,该示例说明如何使用联系人创建适配器,然后使用它来填充具有自定义行的列表视图:
preferences = getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
List<String> contacts = new ArrayList<String>();
// Loop through the shared prefs, adding contacts to our List
for (int i = 0; i < 3; i++) {
String contacts_list = preferences.getString("CONTACT "+i, null);
contacts.add((i+1)+". "+contacts_list);
}
// Create the adapter with contacts
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.listview_row, R.id.list_item, contacts);
// Populate the list
imp_Contacts_List.setAdapter(adapter);
您的自定义listview的行listview_row.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/list_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
</TextView>
</LinearLayout>
注意:确保android:id="@+id/imp_Contacts_List"
在favcontacts_list.xml的内部具有一个列表视图。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句