我正在尝试执行以下任务:
基本上,我的代码的一部分有一个SearchView,它接受来自用户的查询,然后在我的SearchActivity中实例化的Dictionary类中进行查询。然后将这些单词存储到一个数组,该数组又存储在数据库中,然后显示在Fragment类的ListView中。除了当我返回原始活动(使用仿真器的集成后退按钮)时,Fragment类中的ListView并未更新,一切似乎都很好。
但是,当我再次初始化活动时,Fragment类中的ListView确实是最新的。
我尝试了此线程(ViewPager PagerAdapter not updating the View)中建议的流行解决方案,但没有一个起作用。我尝试的一个狡猾的局部解决方案是在每个setOnTabSelectedListener侦听器中设置一个新适配器,但是这消耗了太多资源,并且只有在单击TabLayout时才更新ListView。
这是我的代码,以供参考:
BookSwipe.java(这是管理Fragments和TabLayout的活动)
public class BookSwipe extends AppCompatActivity {
TextView tvTitle;
TextView tvAuthor;
WebView wbDescription;
ImageView ivCover;
CustomAdapter adapter;
String bookTitle;
public void startActivity(Intent intent) {
// check if search intent
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
intent.putExtra("KEY", bookTitle);
}
super.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
TabLayout tabLayout;
final ViewPager viewPager;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book_swipe);
Bundle bundle = getIntent().getExtras();
bookTitle = bundle.getString("data");
System.out.println(bookTitle);
viewPager = (ViewPager) findViewById(R.id.viewPager);
adapter = new CustomAdapter(getSupportFragmentManager(), getActionBar());
viewPager.setAdapter(adapter);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
-- viewPager.setAdapter(adapter);
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
-- viewPager.setAdapter(adapter);
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
-- viewPager.setAdapter(adapter);
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.search2).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
return true;
}
public String getBookTitle() {
return bookTitle;
}
public void setBookTitle(String bookTitle) {
this.bookTitle = bookTitle;
}
private class CustomAdapter extends FragmentStatePagerAdapter {
private String[] fragments = {"Information", "Words", "Quotes"};
public CustomAdapter(FragmentManager supportFragmentManager, ActionBar actionBar) {
super(supportFragmentManager);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new BookProfileFragment(bookTitle);
case 1:
return new BookWordsFragment(bookTitle);
case 2:
return new BookQuotesFragment(bookTitle);
default:
return null;
}
}
@Override
public int getCount() {
return fragments.length;
}
@Override
public CharSequence getPageTitle(int position) {
return fragments[position];
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
}
SearchActivity.java(显示单词的定义)
公共类SearchActivity扩展了AppCompatActivity实现的常量{
TextView dfnDisplay;
private static String LIST_SEPARATOR = "__,__";
public String query;
public String mValue;
MyDBHandler dbHandler;
SQLiteDatabase newDB;
ArrayList stringArray = new ArrayList<>();
Cursor cursor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
dfnDisplay = (TextView) findViewById(R.id.displayDfn);
handleIntent(getIntent());
}
public void saveBtnAction(View view) {
stringArray.add(query);
BookWordsFragment.refreshList(stringArray);
String sendString = convertListToString(stringArray);
dbHandler.addWords(mValue, sendString);
}
protected void onNewIntent(Intent intent) {
handleIntent(intent);
}
private void handleIntent(Intent intent) {
mValue = intent.getStringExtra("KEY");
System.out.println(mValue);
dbHandler = new MyDBHandler(this.getApplicationContext(), null, null, 1);
newDB = dbHandler.getWritableDatabase();
String query2 = "SELECT " + COLUMN_WORDS + " FROM " + TABLE_BOOKS + " WHERE " + COLUMN_BOOK_TITLE + "=\"" + mValue + "\"";
cursor = newDB.rawQuery(query2, null);
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() != true) {
String itemname = cursor.getString(cursor.getColumnIndex("words"));
System.out.println(itemname);
if(itemname != null){
stringArray = (ArrayList) convertStringToList(itemname);
}
break;
}
}
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
query = intent.getStringExtra(SearchManager.QUERY);
dfnDisplay.setText(English.processDefinition(query));
dfnDisplay.setMovementMethod(new ScrollingMovementMethod());
}
}
public static String convertListToString(List<String> stringList) {
StringBuffer stringBuffer = new StringBuffer();
for (String str : stringList) {
stringBuffer.append(str).append(LIST_SEPARATOR);
}
int lastIndex = stringBuffer.lastIndexOf(LIST_SEPARATOR);
stringBuffer.delete(lastIndex, lastIndex + LIST_SEPARATOR.length() + 1);
return stringBuffer.toString();
}
public static List<String> convertStringToList(String str) {
List<String> list = new ArrayList(Arrays.asList(str.split(LIST_SEPARATOR)));
return list;
} }
BookWordsFragment.java(这是存储ListView的片段)
public class BookWordsFragment extends Fragment implements Constants {
MyDBHandler dbHandler;
SQLiteDatabase newDB;
Cursor cursor;
public static ArrayAdapter wordListAdapter;
public ListView wordList;
public String bookTitle;
static List<String> stringArray = new ArrayList<>();
public BookWordsFragment() {
}
public BookWordsFragment(String bookTitle){
this.bookTitle = bookTitle;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_book_words, container, false);
wordList = (ListView) rootView.findViewById(R.id.savedWordsList);
stringArray = populateArray();
wordListAdapter = new CustomListAdapter(getActivity(), R.layout.custom_list, stringArray);
wordList.setAdapter(wordListAdapter);
if(!stringArray.isEmpty()){
}
wordListAdapter.notifyDataSetChanged();
return rootView;
}
public List<String> populateArray(){
List<String> list = new ArrayList();
dbHandler = new MyDBHandler(this.getActivity(), null, null, 1);
newDB = dbHandler.getWritableDatabase();
String query2 = "SELECT " + COLUMN_WORDS + " FROM " + TABLE_BOOKS + " WHERE " + COLUMN_BOOK_TITLE + "=\"" + bookTitle + "\"";
cursor = newDB.rawQuery(query2, null);
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() != true) {
String itemname = cursor.getString(cursor.getColumnIndex("words"));
System.out.println("THIS IS : " + itemname);
if(itemname != null){
list = SearchActivity.convertStringToList(itemname);
System.out.println(stringArray);
}
break;
}
}
return list;
}
public static void refreshList(ArrayList stringArrayCopy){
stringArray = stringArrayCopy;
wordListAdapter.notifyDataSetChanged();
}
@Override
public void onResume() {
super.onResume();
wordListAdapter.notifyDataSetChanged();
}
}
以下是一些图片供参考:Displaying the Fragment
Displaying the definition in SearchActivity
提前非常感谢您。
编辑:
这是我的CustomListAdapter的代码,如注释中所述
class CustomListAdapter extends ArrayAdapter {
private Context mContext;
private int id;
private List<String> items ;
public CustomListAdapter(Context context, int textViewResourceId , List<String> list )
{
super(context, textViewResourceId, list);
mContext = context;
id = textViewResourceId;
items = list ;
}
@Override
public View getView(int position, View v, ViewGroup parent)
{
View mView = v ;
if(mView == null){
LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = vi.inflate(id, null);
}
TextView text = (TextView) mView.findViewById(R.id.textView);
if(items.get(position) != null )
{
text.setTextColor(Color.BLACK);
text.setText(items.get(position));
text.setTextSize(30);
}
return mView;
}
}
最佳答案
在您的CustomListAdapter
类中创建一个方法,例如:
public void setList(ArrayList<String> wordsList) {
items = wordsList; //items is the list you have as a field in adapter.
notifyDatasetChanged();
}
在您的片段
onResume()
中,@Override
public void onResume() {
super.onResume();
stringArray = populateArray();
wordListAdapter.setList(stringArray);
}
编辑:
您必须在适配器中进行一些更改。添加以下方法:
@Override
public int getCount() {
return items.size();
}
@Override
public String getItem(int position) {
return items.get(position);
}