我正在尝试制作一个android词典应用。我有listview,所有单词都在听。我可以搜索单词并获取单词含义(不同活动)。但是,当我从单词含义页面到主页按下后退按钮时,搜索结果消失并且所有(列表视图)单词又回来了,我看不到搜索结果。
如果有人可以帮助我,我将是世界上最幸福的人。
代码:
MainActivity
EditText edit_search = findViewById(R.id.edit_search);
edit_search.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
dictionaryFragment.filterValue(charSequence.toString());
}
@Override
public void afterTextChanged(Editable editable) {
}
});
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); }
@Override
public void onBackPressed() {
DrawerLayout drawer;
drawer = this.<DrawerLayout>findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
我的DictionaryFragment
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
dicList = view.findViewById(R.id.dictionaryList);
adapter = new ArrayAdapter<String>(getContext(), R.layout.kelimelistesi, mSource);
dicList.setAdapter(adapter);
dicList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
if (listener != null)
listener.onItemClick(mSource.get(position));
}
});
}
public void resetDatasource(ArrayList<String> source) {
adapter.clear();
adapter.addAll(source);
adapter.notifyDataSetChanged();
}
public void filterValue(String value) {
adapter.getFilter().filter(value);
如果您需要更多代码,我可以粘贴在这里。您如何看待,我该如何解决?
-----编辑-----
我在这里的所有代码
我的DictionaryFragment
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.google.android.gms.ads.InterstitialAd;
import java.util.ArrayList;
public class DictionaryFragment extends Fragment {
private int top;
private int index;
private FragmentListener listener;
ArrayAdapter<String> adapter;
ListView dicList;
private Adapter mAdapter;
private InterstitialAd mInterstitialAd;
private ArrayList<String> mSource = new ArrayList<String>();
public DictionaryFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_dictionary, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
dicList = view.findViewById(R.id.dictionaryList);
adapter = new ArrayAdapter<String>(getContext(), R.layout.kelimelistesi, mSource);
dicList.setAdapter(adapter);
dicList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
if (listener != null)
listener.onItemClick((String) adapterView.getAdapter().getItem(position));
}
});
}
public void resetDatasource(ArrayList<String> source) {
adapter.clear();
adapter.addAll(source);
adapter.notifyDataSetChanged();
}
public void filterValue(String value) {
adapter.getFilter().filter(value);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void onDetach() {
super.onDetach();
}
public void setOnFragmentListener(FragmentListener listener) {
this.listener = listener;
}
}
我的单词详细信息片段
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.TextView;
public class DetailFragment extends Fragment {
private String value = "";
private TextView tvWord;
private ImageButton btnBookmark, btnVolume;
private WebView tvWordTranslate;
private DBHelper mDBHelper;
private int mDicType;
public DetailFragment() {
// Required empty public constructor
}
public static DetailFragment getNewInstance(String value, DBHelper dbHelper, int dicType) {
DetailFragment fragment = new DetailFragment();
fragment.value = value;
fragment.mDBHelper = dbHelper;
fragment.mDicType = dicType;
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContenView(R.layout.fragment_detail);
}
private void setContenView(int fragment_detail) {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_detail, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
hideKeyboard(getActivity());
setHasOptionsMenu(true);
tvWord = (TextView) view.findViewById(R.id.tvWord);
tvWordTranslate = (WebView) view.findViewById(R.id.tvWordTranslate);
btnBookmark = (ImageButton) view.findViewById(R.id.btnBookmark);
btnVolume = (ImageButton) view.findViewById(R.id.btnVolume);
final Word word = mDBHelper.getWord(value, mDicType);
tvWord.setText(word.key);
tvWordTranslate.loadDataWithBaseURL(null, word.value, "text/html", "utf-8", null);
Word bookmarkWord = mDBHelper.getWordFromBookmark(value);
int isMark = bookmarkWord == null ? 0 : 1;
WebSettings settings = tvWordTranslate.getSettings();
settings.setTextZoom(settings.getTextZoom() + 21);
btnBookmark.setTag(isMark);
int icon = bookmarkWord == null ? R.drawable.ic_bookmark_border : R.drawable.ic_bookmark_fill;
btnBookmark.setImageResource(icon);
btnBookmark.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int i = (int) btnBookmark.getTag();
if (i == 0) {
btnBookmark.setImageResource(R.drawable.ic_bookmark_fill);
btnBookmark.setTag(1);
mDBHelper.addBookmark(word);
} else if (i == 1) {
btnBookmark.setImageResource(R.drawable.ic_bookmark_border);
btnBookmark.setTag(0);
mDBHelper.removeBookmark(word);
}
}
});
btnVolume.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, word.key + (": ") + ("\n") + ("\n") + word.value + ("\n") + ("\n") + ("\n") + getResources().getString(R.string.more) + (": ") + getResources().getString(R.string.apkyolu));
startActivity(Intent.createChooser(shareIntent, getResources().getString(R.string.menu_share)));
}
});
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void onDetach() {
super.onDetach();
}
public static void hideKeyboard(Context context) {
try {
InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
View view = ((Activity) context).getCurrentFocus();
if (view != null) {
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
我的mainActivity
import android.annotation.TargetApi;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.WindowManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import androidx.annotation.RequiresApi;
import androidx.core.view.GravityCompat;
import androidx.appcompat.app.ActionBarDrawerToggle;
import android.view.MenuItem;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.android.material.navigation.NavigationView;
import com.google.android.gms.ads.MobileAds;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.view.Menu;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.ads.InterstitialAd;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
MenuItem menuSetting;
Toolbar toolbar;
private AdView mAdView;
DBHelper dbHelper;
private InterstitialAd mInterstitialAd;
DictionaryFragment dictionaryFragment;
BookmarkFragment bookmarkFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this, getResources().getString(R.string.admob_kullanici_id));
MobileAds.initialize(this, new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
mInterstitialAd = new InterstitialAd(MainActivity.this);
mInterstitialAd.setAdUnitId(getResources().getString(R.string.admob_interstitial));
mInterstitialAd.loadAd(new AdRequest.Builder().build());
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
dbHelper = new DBHelper(this);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
dictionaryFragment = new DictionaryFragment();
bookmarkFragment = BookmarkFragment.getInstance(dbHelper);
goToFragment(dictionaryFragment, true);
dictionaryFragment.setOnFragmentListener(new FragmentListener() {
@Override
public void onItemClick(String value) {
String id = Global.getState(MainActivity.this, "dict_type");
int dicType = id == null ? R.id.ibo : Integer.valueOf(id);
goToFragment(DetailFragment.getNewInstance(value, dbHelper, dicType), false);
}
});
bookmarkFragment.setOnFragmentListener(new FragmentListener() {
@Override
public void onItemClick(String value) {
String id = Global.getState(MainActivity.this, "dict_type");
int dicType = id == null ? R.id.ibo : Integer.valueOf(id);
goToFragment(DetailFragment.getNewInstance(value, dbHelper, dicType), false);
}
});
EditText edit_search = findViewById(R.id.edit_search);
edit_search.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
dictionaryFragment.filterValue(charSequence.toString());
}
@Override
public void afterTextChanged(Editable editable) {
}
});
edit_search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("TAG", "The interstitial wasn't loaded yet.");
}
}
});
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
@Override
public void onBackPressed() {
DrawerLayout drawer;
drawer = this.<DrawerLayout>findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
menuSetting = menu.findItem(R.id.action_settings);
String id = Global.getState(this, "dict_type");
if (id != null)
onOptionsItemSelected(menu.findItem(Integer.valueOf(id)));
else {
ArrayList<String> source = dbHelper.getWord(R.id.ibo);
dictionaryFragment.resetDatasource(source);
}
return true;
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.ibo) {
Global.saveState(this, "dict_type", String.valueOf(id));
ArrayList<String> source = dbHelper.getWord(id);
dictionaryFragment.resetDatasource(source);
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_bookmark) {
String activeFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container).getClass().getSimpleName();
if (!activeFragment.equals(BookmarkFragment.class.getSimpleName())) {
goToFragment(bookmarkFragment, false);
}
}
if (id == R.id.nav_dict) {
String activeFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container).getClass().getSimpleName();
if (!activeFragment.equals(DictionaryFragment.class.getSimpleName())) {
goToFragment(dictionaryFragment, false);
}
}
if (id == R.id.nav_share) {
String shareBody = getResources().getString(R.string.share_title);
Intent shareintent = new Intent();
shareintent.setAction(Intent.ACTION_SEND);
shareintent.putExtra(Intent.EXTRA_SUBJECT, shareBody);
shareintent.putExtra(android.content.Intent.EXTRA_TEXT, getResources().getString(R.string.apkyolu));
shareintent.setType("text/plain");
startActivity(Intent.createChooser(shareintent, getResources().getString(R.string.menu_share)));
}
if (id == R.id.nav_mail) {
Intent i = new Intent(Intent.ACTION_SENDTO);
i.setType("message/rfc822");
i.setData(Uri.parse("mailto:"));
i.putExtra(Intent.EXTRA_EMAIL, new String[]{"dorular@email.com"});
i.putExtra(Intent.EXTRA_SUBJECT, getResources().getString(R.string.mailabout));
i.putExtra(Intent.EXTRA_TEXT, "Write your messsage here...");
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
if (id == R.id.nav_rate) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=PackageName")));
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
void goToFragment(Fragment fragment, boolean isTop) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
if (!isTop)
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
String activeFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container).getClass().getSimpleName();
if (activeFragment.equals(DetailFragment.class.getSimpleName())) {
menuSetting.setVisible(false);
toolbar.findViewById(R.id.edit_search).setVisibility(View.GONE);
toolbar.setTitle(getResources().getString(R.string.app_name));
} else if (activeFragment.equals(BookmarkFragment.class.getSimpleName())) {
menuSetting.setVisible(false);
toolbar.findViewById(R.id.edit_search).setVisibility(View.GONE);
toolbar.setTitle(getResources().getString(R.string.bookmark));
} else {
menuSetting.setVisible(true);
toolbar.findViewById(R.id.edit_search).setVisibility(View.VISIBLE);
toolbar.setTitle("");
}
return true;
}
}