刷新视图片段视图

时间:2017-04-10 13:23:19

标签: android android-fragments refresh

我正在尝试刷新我的片段视图及其中的数据,我试图使视图无效,但它无效。唯一有效的方法是分离和附加片段,但它不是理想的解决方案。我想要更高效的东西。

如果有人建议我更好的解决方案来刷新视图,那对我会有很大的帮助。

谢谢大家

`//注射     @注入     服务;     @注入     SessionManager会话;

// Views
    // User views
@BindView(R.id.user_name) TextView fullName;
@BindView(R.id.user_img) ImageView userImage;
    // Troc views
@BindView(R.id.description) TextView desView;
@BindView(R.id.created_date) TextView createdDate;
@BindView(R.id.title) TextView title;
@BindView(R.id.month) TextView monthPurchaseDate;
@BindView(R.id.year) TextView yearPurchaseDate;
@BindView(R.id.place) TextView address;
@BindView(R.id.actual_price) TextView actualPrice;
@BindView(R.id.original_price) TextView originalPrice;
@BindView(R.id.photo) ImageView postImage;
@BindView(R.id.comments_recycler) RecyclerView commentsRecycler;
@BindView(R.id.send_comment) ImageView sendCommentButton;
@BindView(R.id.text_comment) EditText commentText;
@BindView(R.id.categories_recycler) RecyclerView categoriesRecycler;
@BindView(R.id.close_view) ImageView closeView;
@BindView(R.id.delete_view) ImageView deleteView;
private Socket socket;
private View view;
public TrocDetailsFragmentDialog(Context context, Troc troc){
    this.context = context;
    this.troc = troc;
}


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragment_troc_details_dialog, container, false);
    ((TrocApp)getActivity().getApplication()).getDeps().inject(this);

    ButterKnife.bind(this, view);

    subscriptions = new CompositeSubscription();

   /* view.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
                onTouchEvent(event,v);
            return false;
        }
    });*/

    // Handle other views
    closeView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            TrocDetailsFragmentDialog.this.dismiss();
        }
    });

    deleteView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Snackbar snackbar = Snackbar.make(getView(),R.string.want_to_delete_troc, Snackbar.LENGTH_LONG)
                    .setAction(R.string.undo, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    });
            snackbar.setCallback(new Snackbar.Callback(){
                @Override
                public void onDismissed(Snackbar transientBottomBar, int event) {
                    super.onDismissed(transientBottomBar, event);

                    if(event == Snackbar.Callback.DISMISS_EVENT_TIMEOUT){
                        startDeletingPost(troc.getId());
                    }
                }
            }).show();



        }
    });

 // User
    fullName.setText(troc.getAuthor().getFullName());
    Picasso.with(context)
            .load(BuildConfig.API_SERVER_USER_SMALL_UPLOADS + troc.getAuthor().getPhoto())
            .placeholder(R.drawable.defaultuserlog)
            .error(R.drawable.defaultuserlog)
            .fit()
            .into(userImage);

 // Troc
    title.setText(troc.getTitle());
    desView.setText(troc.getBody());
    address.setText(troc.getAddress().getStreet()+", "+troc.getAddress().getCity()+", "+troc.getAddress().getCountry()+", "+troc.getAddress().getPostalCode());

    // Handle Date of creation of troc
    SimpleDateFormat formattedDate = new SimpleDateFormat(ISO_8601_24H_FULL_FORMAT);
    formattedDate.setTimeZone(TimeZone.getTimeZone("GMT"));

    try {
        Date date = formattedDate.parse(troc.getDateCreated());
        createdDate.setText(new PrettyTime().format( date ));
    } catch (ParseException e) {
        e.printStackTrace();
    }

    if(troc.getPhotos().length > 0) {
        Picasso.with(context)
                .load(BuildConfig.API_SERVER_TROCS_MEDIUM_UPLOADS + troc.getPhotos()[0])
                .placeholder(R.drawable.placeholder_post)
                .error(R.drawable.placeholder_post)
                .resize(400, 400)
                .into(postImage);

        // handle troc image click

        postImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FullScreenImagePagerDialog fullScreenDialog = new FullScreenImagePagerDialog(context, troc.getPhotos());
                fullScreenDialog.setStyle(DialogFragment.STYLE_NORMAL, R.style.DialogFragment);
                fullScreenDialog.show(getFragmentManager(), "dialog");
            }
        });
    }

    // Handle original and actual price

    originalPrice.setText(troc.getOriginalPrice() + " " + Constants.LOCAL_CURRENCY);
    actualPrice.setText(troc.getActualPrice() + " " +Constants.LOCAL_CURRENCY);

    // Handle purchase Date

    handlePurchaseDateView(troc.getPurchaseDate(),monthPurchaseDate,yearPurchaseDate);

    // Handle categories

    handleCategoriesView(categoriesRecycler,troc.getCategories());


    // Make comments area ready

    LinearLayoutManager layoutManager
            = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
    commentsRecycler.setLayoutManager(layoutManager);
    commentsRecycler.setItemAnimator(new DefaultItemAnimator());
    commentsRecycler.setNestedScrollingEnabled(false);
    commentAdapter = new CommentAdapter(context,troc.getComments());
    commentsRecycler.setAdapter(commentAdapter);

    // Handle add comment

    sendCommentButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(commentText.getText().toString().isEmpty()){
                Toast.makeText(context,R.string.specify_comment,Toast.LENGTH_SHORT).show();
            }
            else{
                sendComment(troc.getId(),commentText.getText().toString(),v);
            }
        }
    });

   /* Subscription updateListener = updateSubscription();
    subscriptions.add(updateListener);*/
    socket = IO.socket(URI.create(API_SERVER_ADDRESS));
    socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {

        @Override
        public void call(Object... args) {
            socket.emit("post", troc.getId());

            //  socket.disconnect();
        }

    }).on("post", new Emitter.Listener() {

        @Override
        public void call(Object... args) {
        }

    }).on("postMessage", new Emitter.Listener() {

        @Override
        public void call(final Object... args) {

            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(getContext(),(String)args[0],Toast.LENGTH_SHORT ).show();

                    if(((String)args[0]).equals(SOCKET_POST_STATUS_UPDATED)){
                       updateTrocView();
                   }
                }
            });
        }

    }).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {

        @Override
        public void call(Object... args) {

        }

    });
    socket.connect();
    return view;
}`

我试过的方法

public void updateTrocView(){
    Subscription diplayTrocSubscription = service.getTroc(troc.getId(), new Service.TrocResultServiceCallback() {
        @Override
        public void onSuccess(TrocResult trocResult) {
            if(trocResult.isSuccess()){
                troc = trocResult.getTroc();
                view.invalidate();
                commentAdapter.notifyDataSetChanged();
            }
            else{
               Snackbar.make(view,R.string.check_internet,Snackbar.LENGTH_LONG).show();
            }
        }

        @Override
        public void onError(NetworkError networkError) {

        }
    });
    subscriptions.add(diplayTrocSubscription);
}

2 个答案:

答案 0 :(得分:0)

使用onResume()方法刷新视图和数据。

答案 1 :(得分:0)

将代码改为像这样,

public void updateTrocView() {
        Subscription diplayTrocSubscription = service.getTroc(troc.getId(), new Service.TrocResultServiceCallback() {
            @Override
            public void onSuccess(TrocResult trocResult) {
                if (trocResult.isSuccess()) {
                    troc = trocResult.getTroc();

                    bindDataToUI();
                    //set new Data to commentAdapter
                    commentAdapter.notifyDataSetChanged();
                } else {
                    Snackbar.make(view, R.string.check_internet, Snackbar.LENGTH_LONG).show();
                }
            }

            @Override
            public void onError(NetworkError networkError) {

            }
        });
        subscriptions.add(diplayTrocSubscription);
    }

    private void bindDataToUI() {
        fullName.setText(troc.getAuthor().getFullName());
        Picasso.with(context)
                .load(BuildConfig.API_SERVER_USER_SMALL_UPLOADS + troc.getAuthor().getPhoto())
                .placeholder(R.drawable.defaultuserlog)
                .error(R.drawable.defaultuserlog)
                .fit()
                .into(userImage);

        // Troc
        title.setText(troc.getTitle());
        desView.setText(troc.getBody());
        address.setText(troc.getAddress().getStreet() + ", " + troc.getAddress().getCity() + ", " + troc.getAddress().getCountry() + ", " + troc.getAddress().getPostalCode());

    }