我正在使用viewpager2使用recyclerview适配器。我正在使用api设置每页的textview中的文本,我需要从main activity中定义的按钮获取该文本,第一页工作正常,但之后就无法获取textview了。如何实现这一点?这是我的主要活动代码:
public class MainActivity extends AppCompatActivity {
Toolbar toolbar, searchToolbar;
Menu search_menu;
MenuItem item_search;
ViewPager2 recyclerView;
SwipeRefreshLayout swipeRefreshLayout;
Adapter adapter;
final String API_KEY = "*******";
List<Articles> articles = new ArrayList<>();
TextToSpeech tts;
int positionOfPage;
Boolean first = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setSearchToolbar();
swipeRefreshLayout = findViewById(R.id.swipeRefresh);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setOrientation(ViewPager2.ORIENTATION_VERTICAL);
recyclerView.setOffscreenPageLimit(1);
recyclerView.setPageTransformer(new DepthTransformation());
String country = getCountry();
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION| View.SYSTEM_UI_FLAG_FULLSCREEN|View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
decorView.setSystemUiVisibility(uiOptions);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
retrieveJson("", country, API_KEY);
}
});
retrieveJson("",country, API_KEY);
tts = new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS){
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED){
} else {
convertTextToSpeech();
}
} else {
}
}
});
try {
recyclerView.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
if (first && positionOffset == 0 && positionOffsetPixels == 0){
onPageSelected(0);
first = false;
}
}
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
positionOfPage = position;
}
@Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
}
});
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "Can't check Page", Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_home, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.action_status:
Toast.makeText(MainActivity.this, "page number is" + positionOfPage, Toast.LENGTH_SHORT).show();
convertTextToSpeech();
Toast.makeText(MainActivity.this, "page ggggggg number is" + positionOfPage, Toast.LENGTH_SHORT).show();
return true;
case R.id.action_search:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
circleReveal(R.id.searchToolbar, 1, true, true);
else
searchToolbar.setVisibility(View.VISIBLE);
item_search.expandActionView();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setSearchToolbar() {
searchToolbar = (Toolbar) findViewById(R.id.searchToolbar);
if (searchToolbar != null){
searchToolbar.inflateMenu(R.menu.menu_search);
search_menu = searchToolbar.getMenu();
searchToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
circleReveal(R.id.searchToolbar, 1, true, false);
else
searchToolbar.setVisibility(View.GONE);
}
});
item_search = search_menu.findItem(R.id.action_filter_search);
MenuItemCompat.setOnActionExpandListener(item_search, new MenuItemCompat.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
circleReveal(R.id.searchToolbar, 1, true, false);
} else
searchToolbar.setVisibility(View.GONE);
return true;
}
});
initSearchView();
} else
Log.d("toolbar", "setSearchToolbar:NULL");
}
public void initSearchView() {
final SearchView searchView = (SearchView) search_menu.findItem(R.id.action_filter_search).getActionView();
searchView.setSubmitButtonEnabled(false);
ImageView closeButton = (ImageView) searchView.findViewById(R.id.search_close_btn);
closeButton.setImageResource(R.drawable.ic_baseline_cancel_24);
EditText txtSearch = ((EditText)searchView.findViewById(androidx.appcompat.R.id.search_src_text));
txtSearch.setHint("Search....");
txtSearch.setHintTextColor(Color.DKGRAY);
txtSearch.setTextColor(getResources().getColor(R.color.white));
AutoCompleteTextView searchTextView = (AutoCompleteTextView) searchView.findViewById(androidx.appcompat.R.id.search_src_text);
try {
Field mCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");
mCursorDrawableRes.setAccessible(true);
mCursorDrawableRes.set(searchTextView, R.drawable.ic_baseline_search_24);
} catch (Exception e) {
e.printStackTrace();
}
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
callSearch(query);
searchView.clearFocus();
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
callSearch(newText);
return true;
}
public void callSearch(String query){
if (!query.equals("")){
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
retrieveJson(query, getCountry(), API_KEY);
}
});
retrieveJson(query,getCountry(), API_KEY);
}else {
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
retrieveJson("", getCountry(), API_KEY);
}
});
retrieveJson("",getCountry(), API_KEY);
}
Log.i("query", "" + query);
}
});
}
public void circleReveal(int viewID, int posFromRight, boolean containsOverflow, final boolean isShow){
final View myView = findViewById(viewID);
int width = myView.getWidth();
if (posFromRight > 0)
width -= (posFromRight*getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_material)) - (getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_material)/2);
int cx = width;
int cy = myView.getHeight()/2;
Animator anim;
if (isShow)
anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, 0, (float)width);
else
anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, (float)width, 0);
anim.setDuration((long)220);
anim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (!isShow){
super.onAnimationEnd(animation);
myView.setVisibility(View.GONE);
}
}
});
if (isShow)
myView.setVisibility(View.VISIBLE);
anim.start();
}
public void retrieveJson(String query, String country, String apiKey) {
swipeRefreshLayout.setRefreshing(true);
Call<Headlines> call;
if (!query.equals("")) {
call = ApiClient.getInstance().getApi().getSpecificData(query, apiKey);
} else {
call = ApiClient.getInstance().getApi().getHeadlines(country, apiKey);
}
call.enqueue(new Callback<Headlines>() {
@Override
public void onResponse(Call<Headlines> call, Response<Headlines> response) {
if (response.isSuccessful()) {
assert response.body() != null;
if (response.body().getArticles() != null) {
swipeRefreshLayout.setRefreshing(false);
articles.clear();
articles = response.body().getArticles();
adapter = new Adapter(MainActivity.this, articles);
recyclerView.setAdapter(adapter);
}
}
}
@Override
public void onFailure(Call<Headlines> call, Throwable t) {
swipeRefreshLayout.setRefreshing(false);
}
});
}
public String getCountry() {
Locale locale = Locale.getDefault();
String country = locale.getCountry();
return country.toLowerCase();
}
@Override
protected void onPause() {
if (tts != null){
tts.stop();
tts.shutdown();
}
super.onPause();
}
private void convertTextToSpeech() {
try {
String mySpeech = getTextForSpeech();
if (mySpeech == null||"".equals(mySpeech)){
mySpeech = "content Not Available";
tts.speak(mySpeech, TextToSpeech.QUEUE_FLUSH, null);
} else {
tts.speak(mySpeech , TextToSpeech.QUEUE_FLUSH, null);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private String getTextForSpeech (){
View vf = recyclerView.getChildAt(positionOfPage);
TextView tV = (TextView)vf.findViewById(R.id.tvContent);
String dataToSpeak = tV.getText().toString();
return dataToSpeak;
}
}以下是我的适配器代码:
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
Context context;
List<Articles> articles;
public Adapter(Context context, List<Articles> articles) {
this.context = context;
this.articles = articles;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.items, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
final Articles a = articles.get(position);
String url = a.getUrl();
holder.tvTitle.setText(a.getTitle());
holder.tvSource.setText(a.getSource().getName());
holder.tvDate.setText("\u2022"+dateTime(a.getPublishedAt()));
holder.tvContent.setText(a.getDescription());
String imageUrl = a.getUrlToImage();
Picasso.get().load(imageUrl).into(holder.imageView);
holder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, DetailedActivity.class);
intent.putExtra("title", a.getTitle());
intent.putExtra("source", a.getSource().getName());
intent.putExtra("time", dateTime(a.getPublishedAt()));
intent.putExtra("imageUrl", a.getUrlToImage());
intent.putExtra("url", a.getUrl());
intent.putExtra("desc", a.getDescription());
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return articles.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvTitle, tvSource, tvDate, tvContent;
ImageView imageView;
CardView cardView;
public ViewHolder(@NonNull View itemView) {
super(itemView);
tvTitle = itemView.findViewById(R.id.tvTitle);
tvSource = itemView.findViewById(R.id.tvSource);
tvDate = itemView.findViewById(R.id.tvDate);
imageView = itemView.findViewById(R.id.image);
tvContent = itemView.findViewById(R.id.tvContent);
cardView = itemView.findViewById(R.id.cardView);
}
}
public String dateTime(String t){
PrettyTime prettyTime = new PrettyTime(new Locale(getCountry()));
String time = null;
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:", Locale.ENGLISH);
Date date = simpleDateFormat.parse(t);
time = prettyTime.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return time;
}
public String getCountry() {
Locale locale = Locale.getDefault();
String country = locale.getCountry();
return country.toLowerCase();
}
}
暂无答案!
目前还没有任何答案,快来回答吧!