我正在做一个西班牙新闻应用程序,看这里:
这个应用程序的问题是,每当任何用户点击like、play audio或translate按钮时,recyclerView就会跳到顶部。
>
数据以片段形式从Firebase实时数据库中获取。请帮帮忙。
@override public View onCreateView(LayoutInfluater Influater,ViewGroup container,Bundle savedInstanceState){//为此片段充气mView=inflater.Inflate(r.layout.fragment_feed,container,false);
MobileAds.initialize(mView.getContext(), "XXXXXXXXX");
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(mView.getContext());
mRewardedVideoAd.setRewardedVideoAdListener(this);
loadRewardedVideoAd();
mAuth = FirebaseAuth.getInstance();
feedRecycler = mView.findViewById(R.id.recycler_feed);
feedRecycler.setLayoutManager(new LinearLayoutManager(getContext()));
RecyclerView.Adapter adapter = new FeedAdapter(mView.getContext(),mRecyclerViewItems);
feedRecycler.setAdapter(adapter);
userImage = mView.findViewById(R.id.feed_img);
username = mView.findViewById(R.id.feed_name);
usercomment = mView.findViewById(R.id.feed_edittext);
subMitComment = mView.findViewById(R.id.feed_submit);
mUSerCmt = FirebaseDatabase.getInstance().getReference().child("feeds");
mScoreRef = FirebaseDatabase.getInstance().getReference().child("scores");
if(mAuth.getCurrentUser().getPhotoUrl()!= null) {
Picasso.get().load(mAuth.getCurrentUser().getPhotoUrl().toString()).into(userImage);
username.setText(mAuth.getCurrentUser().getDisplayName());
} else {
startActivity(new Intent(mView.getContext(),UserProfile.class));
}
subMitComment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String usercmt = usercomment.getText().toString();
if(!usercmt.equals("")){
writeNewPost(usercmt,mAuth.getUid(),mAuth.getCurrentUser().getDisplayName(),mAuth.getCurrentUser().getPhotoUrl().toString());
Toast.makeText(mView.getContext(),"Comment updated!",Toast.LENGTH_SHORT).show();
}
usercomment.setText("");
}
});
mUSerCmt.orderByChild("timestamp").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
mRecyclerViewItems.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
Model_Feed epiModel = dataSnapshot1.getValue(Model_Feed.class);
mRecyclerViewItems.add(epiModel);
}
FeedAdapter = new FeedAdapter(mView.getContext(), mRecyclerViewItems);
feedRecycler.setAdapter(FeedAdapter);
FeedAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
return mView;
}
private void writeNewPost(String sen, String uid, String name, String img) {
// Create new post at /user-posts/$userid/$postid and at
// /posts/$postid simultaneously
String key = mUSerCmt.push().getKey();
long time = System.currentTimeMillis() * (-1);
Model_Feed post = new Model_Feed(sen,time,uid, name, img,key);
Map<String, Object> postValues = post.toMap();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put(key, postValues);
mUSerCmt.updateChildren(childUpdates);
}
public class FeedAdapter extends RecyclerView.Adapter<FeedAdapter.FeedViewHolder>{
private Context context;
private List<Object> mRecyclerViewItems;
public FeedAdapter(Context context, List<Object> mRecyclerViewItems) {
this.context = context;
this.mRecyclerViewItems = mRecyclerViewItems;
}
@NonNull
@Override
public FeedViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.rec_words,viewGroup,false);
return new FeedViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final FeedViewHolder feedViewHolder, int i) {
final Model_Feed modelFeed = (Model_Feed) mRecyclerViewItems.get(i);
Picasso.get().load(modelFeed.getImg()).into(feedViewHolder.circleImageView);
feedViewHolder.nameWord.setText(modelFeed.getName());
feedViewHolder.statusword.setText(modelFeed.getSen());
feedViewHolder.fireword.setText(String.valueOf(modelFeed.fires.size()));
feedViewHolder.playword.setText(String.valueOf(modelFeed.plays.size()));
if(modelFeed.fires.containsKey(mAuth.getUid())){
feedViewHolder.fireimage.setImageDrawable(getResources().getDrawable(R.drawable.fire));
}
if(modelFeed.plays.containsKey(mAuth.getUid())){
feedViewHolder.playimage.setImageDrawable(getResources().getDrawable(R.drawable.play_button));
}
feedViewHolder.fireLinear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
feedViewHolder.fireimage.setImageDrawable(getResources().getDrawable(R.drawable.fire));
onFireClicked(mUSerCmt.child(modelFeed.getKey()),modelFeed.getUid());
}
});
feedViewHolder.playLinear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
feedViewHolder.playimage.setImageDrawable(getResources().getDrawable(R.drawable.play_button));
sen_sound = modelFeed.getSen();
mScoreRef.child(mAuth.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
final Model_Score modelScore = dataSnapshot.getValue(Model_Score.class);
long scoreCheck = modelScore.getScore();
if (scoreCheck < 1 ){
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(context, android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(context);
}
builder.setTitle("Insufficient Coins")
.setMessage("You've insufficient coins in your wallet to listen this audio, Watch a reward video complete and get 50 coins.")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
long score = modelScore.getScore() + 5;
Model_Score modelScore1 = new Model_Score(score, modelScore.getReput(), mAuth.getUid());
mScoreRef.child(mAuth.getUid()).setValue(modelScore1);
}
scorez = modelScore.getScore();
reputz = modelScore.getReput();
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(mView.getContext(),"Our Apologies for inconvenience",Toast.LENGTH_SHORT).show();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}else {
long score = modelScore.getScore() - 10;
Model_Score modelScore1 = new Model_Score(score, modelScore.getReput(), mAuth.getUid());
mScoreRef.child(mAuth.getUid()).setValue(modelScore1);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
});
}
@Override
public int getItemCount() {
return mRecyclerViewItems.size();
}
public class FeedViewHolder extends RecyclerView.ViewHolder{
CircleImageView circleImageView;
TextView nameWord, statusword,fireword,playword;
LinearLayout fireLinear, playLinear;
ImageView fireimage, playimage;
public FeedViewHolder(@NonNull View itemView) {
super(itemView);
circleImageView = itemView.findViewById(R.id.word_image);
nameWord = itemView.findViewById(R.id.word_name);
statusword = itemView.findViewById(R.id.word_status);
fireword = itemView.findViewById(R.id.word_text_fire);
playword = itemView.findViewById(R.id.word_text_play);
fireLinear = itemView.findViewById(R.id.word_fire_linear);
playLinear = itemView.findViewById(R.id.word_play_linear);
fireimage = itemView.findViewById(R.id.word_img_fire);
playimage = itemView.findViewById(R.id.word_img_play);
}
}
}
void sendReward(long scores, long reputs){
long score = scores + 50;
Model_Score modelScore1 = new Model_Score(score, reputs, mAuth.getUid());
mScoreRef.child(mAuth.getUid()).setValue(modelScore1);
}
void showToast(String msg){
Toast.makeText(mView.getContext(),msg,Toast.LENGTH_SHORT).show();
}
private void onFireClicked(DatabaseReference postRef, final String cr_uid) {
postRef.runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData mutableData) {
Model_Feed p = mutableData.getValue(Model_Feed.class);
if (p == null) {
return Transaction.success(mutableData);
}
if (p.fires.containsKey(mAuth.getUid())) {
// Unstar the post and remove self from stars
p.firecount = p.firecount - 1;
p.fires.remove(mAuth.getUid());
} else {
// Star the post and add self to stars
p.firecount = p.firecount + 1;
p.fires.put(mAuth.getUid(), true);
mScoreRef.child(cr_uid).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Model_Score modelScore = dataSnapshot.getValue(Model_Score.class);
long reput = modelScore.getReput();
Model_Score modelScore1 = new Model_Score(modelScore.getScore(), reput + 10, cr_uid);
mScoreRef.child(cr_uid).setValue(modelScore1);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
// Set value and report transaction success
mutableData.setValue(p);
return Transaction.success(mutableData);
}
@Override
public void onComplete(DatabaseError databaseError, boolean b,
DataSnapshot dataSnapshot) {
// Transaction completed
//Log.d(TAG, "postTransaction:onComplete:" + databaseError);
}
});
}
private void onPlayClicked(DatabaseReference postRef) {
postRef.runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData mutableData) {
Model_Feed p = mutableData.getValue(Model_Feed.class);
if (p == null) {
return Transaction.success(mutableData);
}
if (p.plays.containsKey(mAuth.getUid())) {
// Unstar the post and remove self from stars
p.playcount = p.playcount + 1;
p.plays.put(mAuth.getUid() + p.playcount,true);
new readSen().execute();
} else {
// Star the post and add self to stars
p.playcount = p.playcount + 1;
p.plays.put(mAuth.getUid(), true);
}
// Set value and report transaction success
mutableData.setValue(p);
return Transaction.success(mutableData);
}
@Override
public void onComplete(DatabaseError databaseError, boolean b,
DataSnapshot dataSnapshot) {
// Transaction completed
//Log.d(TAG, "postTransaction:onComplete:" + databaseError);
}
});
}
每当您设置新适配器时,recyclerview
就会删除和分离旧适配器。相反,您可以尝试只更新当前适配器上的数据,其中一个简单的方法是在适配器上创建一个公共方法来重新分配数据:
public class FeedAdapter extends RecyclerView.Adapter<FeedAdapter.FeedViewHolder> {
// ...
public void setItems(List<Object> items) {
mRecyclerViewItems = items;
}
// ...
}
然后在OnDataChange
回调中更新适配器:
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
mRecyclerViewItems.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
Model_Feed epiModel = dataSnapshot1.getValue(Model_Feed.class);
mRecyclerViewItems.add(epiModel);
}
if (FeedAdapter != null) {
FeedAdapter.setItems(mRecyclerViewItems);
FeedAdapter. notifyDataSetChanged();
} else {
FeedAdapter = new FeedAdapter(mView.getContext(), mRecyclerViewItems);
feedRecycler.setAdapter(FeedAdapter);
}
}
问题内容: 这是我的onCreate,它处理适配器,LinearLayoutManager等。我尝试了每个选项以尝试将其滚动到顶部,但不能。我什至尝试创建自己的自定义LinearLayoutManager。 问题答案: 您尝试过还是? RecyclerView不会在其中实现任何滚动逻辑,而是更加具体,它会根据实现的布局转到特定的索引,在您的情况下是线性的。
问题内容: 我的问题是当我在回收视图中滚动数据时,所以加载了新数据,但问题是当新数据加载时,回收视图从第一个产品开始, 我需要保持旧的位置,只滚动新数据,而不滚动所有旧数据 目前,我正在添加文件adeptoer文件和主文件的完整代码, 问题答案: 试试这个:
最近,当按下新的ViewController时,我的应用程序开始进行滚动跳跃,如下所示: 我尝试过不同的答案,但似乎没有任何效果。我已经了解到,我的应用程序设置负偏移到后,我设置: } 我试图找到什么是设置偏移量,我已经了解到setContentOffset它是从调用:
我对jQuery移动锚有问题。当我点击带有某个锚的_blank链接时,我会重定向到新选项卡中的新页面并导航到锚链接。但是当页面完全加载时,页面跳转到页面顶部
我一直在寻找一个适当的API来做我需要做的事情,我几乎可以肯定的是,必须有一个API。但我找不到。 提前致谢
我试过使用descendantFocusability=“blocksdescendents”,但这不起作用。 这是我的XML代码,可以在其中找到RecyclerView 用于向RecyclersView添加数据的代码是 所有应用程序都工作得很好,唯一的问题是滚动行为。当我在HIM中添加新数据时,我希望滚动位置不会出现在RecyclersView列表的顶部。