2016-05-17 6 views
1

Работаю над приложением, в котором реализована кнопка FOLLOW внутри View-пейджера.Изменение изображения кнопки после ответа с сервера

Когда пользователь нажимает кнопку FOLLOW, кнопка должна измениться на FOLLOWING после получения ответа от сервера.

Хотя я его реализовал ... Изображение кнопки не изменяется после того, как click.it имеет очень необычное поведение.

Иногда он показывает ПОСЛЕДУЮЩИЕ действия после перезагрузки или слайдов пейджера. Ниже мой код ..

package comend.com.comendify.adapters; 
    import android.content.Context; 
    import android.content.Intent; 
    import android.support.v4.view.PagerAdapter; 
    import android.util.Log; 
    import android.view.LayoutInflater; 
    import android.view.View; 
    import android.view.ViewGroup; 
    import android.widget.Button; 
    import android.widget.ImageView; 
    import android.widget.LinearLayout; 
    import android.widget.RelativeLayout; 
    import android.widget.TextView; 
    import android.widget.Toast; 
    import com.squareup.picasso.Picasso; 

    import java.util.ArrayList; 
    import comend.com.comendify.R; 
    import comend.com.comendify.activity.ActViewUserProfile; 
    import comend.com.comendify.models.Home; 
    import comend.com.comendify.models.Tags; 
    import comend.com.comendify.models.User; 
    import  comend.com.comendify.serverCommunication.WebServerSetGetUserActivities; 
    import comend.com.comendify.utility.RoundedImageView; 
    import comend.com.comendify.utility.UserJSONUtils; 
    import comend.com.comendify.utility.Utils; 

    /** 
    * Created by qamar on 14-03-2016. 
    */ 
    public class ImageViewPagerAdapter extends PagerAdapter { 
    public static final String TAG = ImageViewPagerAdapter.class.getSimpleName(); 
    Context mContext; 
    LayoutInflater mLayoutInflater; 
    private ArrayList<String> imageList; 
    private ArrayList<Home> home_arrayList; 
    private String loggedInUserId; 
    private Button btnFollow,btnUnFollow; 
    int resourceId; 
    int START_INDEX; 
    private User userLogged; 
    private View itemView ; 
    Boolean val =true; 
    private boolean isFollowing = true; 
    boolean isIconChange; 

    public ImageViewPagerAdapter(Context context, ArrayList<String> imageList, int START_INDEX, int resoursceId, ArrayList<Home> home_arrayList) { 
    mContext = context; 
    this.imageList =imageList; 
    this.home_arrayList = home_arrayList; 
    this.resourceId = resoursceId; 
    this.START_INDEX = START_INDEX; 
    mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    loggedInUserId = Utils.getLoggedInUserId(mContext); 
    Log.d(TAG,"In ImageViewAdapter: " +START_INDEX+" "+home_arrayList); 
} 

@Override 
public int getCount() { 

    if(resourceId == R.layout.item_show_image_pager) { 
     return imageList.size(); 
    } 
     return home_arrayList.size(); 

} 

@Override 
public boolean isViewFromObject(View view, Object object) { 
    if(resourceId == R.layout.item_home_pager_profile){ 
     return view ==((RelativeLayout)object); 
    } 
    return view == ((LinearLayout) object); 
} 

@Override 
public Object instantiateItem(ViewGroup container, final int position) { 
    Log.d(TAG,"In InstantiateItem" + position); 

    if(resourceId == R.layout.item_show_image_pager) { 
     itemView = mLayoutInflater.inflate(R.layout.item_show_image_pager, container, false); 
     Log.d(TAG, "In viewImage " + position + " " + START_INDEX); 
     ImageView imageView = (ImageView) itemView.findViewById(R.id.iv_asi_image); 

     Picasso.with(mContext).load(imageList.get(position)) 
       .fit() 
       .centerCrop() 
       .error(R.drawable.logo_splash) 
       .into(imageView); 
     container.addView(itemView); 
    }else if(resourceId == R.layout.item_home_pager_header){ 
     Log.d(TAG, "In homeImageHeader " + position + " " + START_INDEX); 
     itemView = mLayoutInflater.inflate(R.layout.item_home_pager_header, container, false); 
     ImageView imageView = (ImageView) itemView.findViewById(R.id.iv_home_image_header); 
     Picasso.with(mContext).load(String.valueOf(home_arrayList.get(position).getEnt_image())) 
       .fit() 
       .centerCrop() 
       .error(R.drawable.logo_splash) 
       .into(imageView); 
     container.addView(itemView); 

     itemView.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       int fragId = 2; 

       Intent intent = new Intent(mContext, ActViewUserProfile.class); 
       intent.putExtra("item_id", home_arrayList.get(position).ent_id); 
       intent.putExtra("frag_id", fragId); 
       intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
       mContext.startActivity(intent); 
       Toast.makeText(mContext, "complete item clicked", Toast.LENGTH_LONG).show(); 
      } 
     }); 
    }else if(resourceId == R.layout.item_home_pager_profile){ 
     //here is the problem in yhis layout 
     Log.d(TAG, "In homeUserProfile " +home_arrayList); 
     itemView = mLayoutInflater.inflate(R.layout.item_home_pager_profile,container,false); 
     //function for setting all the elements of item 
     setUserCommends(itemView, position); 
     container.addView(itemView); 



     itemView.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       Log.d(TAG,"In ItemView Clicked"); 
       int fragId = 3; 

       Intent intent = new Intent(mContext, ActViewUserProfile.class); 
       intent.putExtra("commend_id", home_arrayList.get(position).getUser_commend_id()); 
       intent.putExtra("frag_id", fragId); 
       intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
       mContext.startActivity(intent); 
       Toast.makeText(mContext, "complete item clicked", Toast.LENGTH_LONG).show(); 
      } 
     }); 
    } 


    return itemView; 
} 

@Override 
public void destroyItem(ViewGroup container, int position, Object object) { 
    if(resourceId ==R.layout.item_show_image_pager) { 
     container.removeView((LinearLayout) object); 
    }else if(resourceId == R.layout.item_home_pager_profile){ 
     container.removeView((RelativeLayout)object); 
     //container.removeViewAt(position); 
     Log.d(TAG,"In destroy Item " +container.getChildCount()); 

    } 

} 

//method for setting all the elements 
private void setUserCommends(View itemView, final int position){ 
    Log.d(TAG,"In homeprofile setUserCommends " +position); 
    //Log.d(TAG,"In homeProfile1" +home_arrayList.get(position).getUser_product_image() +" "+home_arrayList.get(position).getUser_image()); 
    ImageView ivProductImage  = (ImageView) itemView.findViewById(R.id.iv_hpp_product_pic); 
    TextView tvProductName   = (TextView) itemView.findViewById(R.id.tv_hpp_product_name); 
    TextView tvProductDesc   = (TextView) itemView.findViewById(R.id.tv_hpp_description); 
    RoundedImageView ivUserImage = (RoundedImageView) itemView.findViewById(R.id.iv_hpp_user_profile_pic); 
    TextView tvUserName   = (TextView) itemView.findViewById(R.id.tv_hpp_profile_name); 
    btnFollow      = (Button) itemView.findViewById(R.id.btn_hpp_follow); 
    // btnUnFollow = (Button) itemView.findViewById(R.id.btn_hpp_unfollow); 

    userLogged = new User(); 
    userLogged.setmUserName(home_arrayList.get(position).getUser_name()); 
    userLogged.setmImageUrl(home_arrayList.get(position).getUser_image()); 
    userLogged.setmFirstName(home_arrayList.get(position).getUser_name()); 

    //checking for the buttons for each slides or when the screen first turns up 
    if(home_arrayList.get(position).getIs_following()== 0){ 
     Log.d(TAG, "In check if " + home_arrayList.get(position).getIs_following()); 
     btnFollow.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.profile_follow, 0, 0, 0); 

    }else{ 
     Log.d(TAG, "In check else " + home_arrayList.get(position).getIs_following()); 
     btnFollow.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.profile_following, 0, 0, 0); 

    } 

    if(!home_arrayList.get(position).getUser_product_image().isEmpty()) { 
     setImageWithPicasso(ivProductImage, home_arrayList.get(position).getUser_product_image()); 
    } 
    if(!home_arrayList.get(position).getUser_image().isEmpty()){ 
     setImageWithPicasso(ivUserImage, home_arrayList.get(position).getUser_image()); 
    } 
    tvProductName.setText(home_arrayList.get(position).getUser_product_name()); 
    tvProductDesc.setText(home_arrayList.get(position).getUser_commend_review()); 
    tvUserName.setText(home_arrayList.get(position).getUser_name()); 

    ivUserImage.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Log.d(TAG,"In userImage Clicked"); 
      int fragId = 1; 

      Intent intent = new Intent(mContext, ActViewUserProfile.class); 
      intent.putExtra("user_id", home_arrayList.get(position).getUser_id()); 
      intent.putExtra("frag_id", fragId); 
      intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
      mContext.startActivity(intent); 
      Toast.makeText(mContext, "complete item clicked", Toast.LENGTH_LONG).show(); 
     } 
    }); 
    //isFollowing = false; 
    //puttong the clickListener on the follow button 
    btnFollow.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Log.d(TAG,"In btnFollow Clicked"); 
      //isIconC =!isIconChange; 


       if (isFollowing =true) { 
        Log.d(TAG, "in isFollowing"); 
        isFollowing =false; 
        btnFollow.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.profile_follow, 0, 0, 0); 
        unFollowUser(home_arrayList.get(position).getUser_id(), position); 
       } else { 
        Log.d(TAG, "in isNotFollowing"); 
        isFollowing = true; 
        btnFollow.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.profile_following, 0, 0, 0); 
        btnFollow.setText("UNFOLLOW"); 
        //btnFollow.setEnabled(false); 
        followerUser(home_arrayList.get(position).getUser_id(), position); 

       } 
     } 
    }); 

} 

private void setImageWithPicasso(ImageView imageView, String user_product_image){ 
    Picasso.with(mContext).load(user_product_image) 
      .fit() 
      .centerCrop() 
      .error(R.drawable.logo_splash) 
      .into(imageView); 
} 

//Method for Following user 
private void followerUser(String user_id, int position) { 
    final int FOLLOW_TAG = 0; 
    UserJSONUtils userJSONUtils = new UserJSONUtils(mContext); 
    String json =userJSONUtils. setDataToJson(userLogged,user_id); 
    //call the method to follow 
    callToServerToFollow(json, FOLLOW_TAG,position); 

} 

//method for UnFollowing user 
private void unFollowUser(String user_id, int position){ 
    final int UNFOLLOW_TAG = 1; 
    UserJSONUtils userJSONUtils = new UserJSONUtils(mContext); 
    String json = userJSONUtils.setDataToJson(userLogged,user_id); 
    //calling the method to follow 
    callToServerToFollow(json, UNFOLLOW_TAG,position); 
} 

// method for calling server 
public void callToServerToFollow(String json,int TAG_FOLL,int position){ 


    WebServerSetGetUserActivities webServerSetGetUserActivities = new WebServerSetGetUserActivities(mContext,btnFollow,btnUnFollow,null,null); 
    webServerSetGetUserActivities.addFollowUnFollow(json, TAG_FOLL, Tags.ACT_TAG.ACT_HOME_FEED,home_arrayList,position); 
} 

}

очень признателен за любую помощь.

+1

Где мой код? –

+0

Что вы пытаетесь сделать, это настроить кнопку для успеха с изображением на сервере. это ???? –

+0

yeah Pramod..После того как я получаю сообщение об успешном ответе от сервера, моя кнопка Follow изменит его образ на следующую заметку: - моя кнопка находится внутри пейджера представления – rehan

ответ

0

Примечание. Фрагменты состояния на ViewPager инициализируются фрагментом раньше. , то есть, если в ViewPager используются три фрагмента A, B, C, состояние B инициализируется в A во время просмотра пользователя, C также те же, когда B находится в представлении пользователя. Существует два способа решения этой проблемы: 1) использовать A Fragment для реализации метода запроса для ответа и установить публичное логическое значение для получения результата ответа true, а затем в фрагменте B, где требуется событие кнопки, проверьте наличие логического результата. 2) В вашем классе AppController проверьте результат из фрагмента A и установите фрагмент B. Это всегда будет поддерживать результат, даже если приложение включено. проверьте этот http://www.androidhive.info/2014/05/android-working-with-volley-library-1/ для реализации класса AppController.

Смежные вопросы