I want to use admob with recyclerview but there is a problem. I need to hide some elements that are belong to viewholder. I need to hide the imageview in which position the ImageView belongs. When i click holder.btnReklamIzle the picture in that position must be hid in onRewardedVideoAdLoaded method. How can i transmit the position to onRewardedVideoAdLoaded method?
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_kuponlar, container, false);
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(KuponlarFragment.this.getActivity());
mRewardedVideoAd.setRewardedVideoAdListener(this);
tahminlerRecyclerView = root.findViewById(R.id.tahminlerRecyclerView);
linearLayoutManager = new LinearLayoutManager(this.getActivity());
tahminlerRecyclerView.setLayoutManager(linearLayoutManager);
tahminlerRecyclerView.setHasFixedSize(true);
loadRewardedVideoAd();
fetch();
return root;
}
private void loadRewardedVideoAd() {
mRewardedVideoAd.loadAd(getString(R.string.admob_ads_id),
new AdRequest.Builder().build());
}
private void fetch() {
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("tahminler");
FirebaseRecyclerOptions<Mac> options =
new FirebaseRecyclerOptions.Builder<Mac>()
.setQuery(query, new SnapshotParser<Mac>() {
#NonNull
#Override
public Mac parseSnapshot(#NonNull DataSnapshot snapshot) {
return new Mac((double)snapshot.child("oran").getValue(),
snapshot.child("tahmin").getValue().toString(),
);
}
})
.build();
adapter = new FirebaseRecyclerAdapter<Mac, ViewHolder>(options) {
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.tahmin_tasarim_recyclerview, parent, false);
return new ViewHolder(view);
}
#Override
protected void onBindViewHolder(final ViewHolder holder, final int position, Mac mac) {
holder.btnReklamIzle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
}
}});
}
};
tahminlerRecyclerView.setAdapter(adapter);
}
#Override
public void onRewardedVideoAdLoaded() {
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView image;
public ViewHolder(View itemView) {
super(itemView);
image = itemView.findViewById(R.id.image);
}
}
onRewardedVideoAdLoaded is a callback method for an asynchronous operation hence you cannot pass values to it as arguments but use referenced variables.
For your case do the following:
Firstly
Create a global variable to hold the list of views to hide
ArrayList<View> views_to_hide = new ArrayList<>();
Secondly
Create a helper function to hide the views
function hideViews(ArrayList<View> views){
for(View v : views) v.setVisibility(View.GONE);
}
Thirdly
Inside onBindViewHolder Add to the list the views you want to hide under your button onClick
public void onClick(View v) {
//...
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
// Ads already shown you may want to manually hide other images here
}else{
// We only need to add to list when ads not loaded
// We also want to make sure we don't add same view to the list twice
if(!views_to_hide.contains(holder.image))
views_to_hide.add(holder.image);
}});
//...
Finally
Call your helper function inside onRewardedVideoAdLoaded
#Override
public void onRewardedVideoAdLoaded() {
//This hides the views that was added to the list before now
hideViews(views_to_hide);
}
Related
I am using navigation component in my app I have 2 fragments one fragments list of items and another shows detail of an item when user clicks on an item in fragments 1 it goes to detail fragment and when I switch back to first fragment then all the listing duplicates again.
Below is my code:
CakeFragment.java
public class CakeFragment extends Fragment {
List<AllCakes> allCakeList = new ArrayList<>();
AllCakesAdapter adapter;
BottomNavigationView navView;
FragmentCakeBinding fragmentCakeBinding;
public CakeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
fragmentCakeBinding = FragmentCakeBinding.inflate(inflater,container,false);
navView = getActivity().findViewById(R.id.navView);
navView.setVisibility(View.GONE);
getAllCakes();
return fragmentCakeBinding.getRoot();
}
private void getAllCakes(){
Retrofit retrofit = RetrofitClient.getInstance();
ApiService apiService = retrofit.create(ApiService.class);
Call<List<AllCakes>> call = apiService.getAllCake();
call.enqueue(new Callback<List<AllCakes>>() {
#Override
public void onResponse(Call<List<AllCakes>> call, Response<List<AllCakes>> response) {
fragmentCakeBinding.cakeProgress.setVisibility(View.INVISIBLE);
fragmentCakeBinding.allCakeRecycler.setHasFixedSize(true);
fragmentCakeBinding.allCakeRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));
allCakeList.addAll(response.body());
adapter = new AllCakesAdapter(getActivity(),allCakeList);
fragmentCakeBinding.allCakeRecycler.setAdapter(adapter);
}
#Override
public void onFailure(Call<List<AllCakes>> call, Throwable t) {
fragmentCakeBinding.cakeProgress.setVisibility(View.INVISIBLE);
TastyToast.makeText(getActivity(),t.getMessage(),TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
}
});
}
}
AllCakesAdapter.java
public class AllCakesAdapter extends RecyclerView.Adapter<AllCakesAdapter.ViewHolder> {
Context context;
List<AllCakes> allCakeList;
public AllCakesAdapter(Context context, List<AllCakes> allCakeList) {
this.context = context;
this.allCakeList = allCakeList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.allcakes_row,parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
AllCakes model = allCakeList.get(position);
Glide.with(context).load(model.getImgurl()).into(holder.allCakeImg);
holder.allCakeName.setText(model.getName());
holder.cakeDisPrice.setPaintFlags(holder.cakeDisPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
holder.moreCake.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NavController navController = Navigation.findNavController((Activity) context,R.id.fragment);
navController.navigate(R.id.cakeDetailFragment);
}
});
}
#Override
public int getItemCount() {
return allCakeList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView allCakeImg;
Button moreCake;
TextView allCakeName;
public ViewHolder(#NonNull View itemView) {
super(itemView);
allCakeImg = itemView.findViewById(R.id.allCakeImg);
moreCake = itemView.findViewById(R.id.moreCake);
allCakeName = itemView.findViewById(R.id.allCakeName);
}
}
}
CakeDetailFragment.java
public class CakeDetailFragment extends Fragment {
FragmentCakeDetailBinding fragmentCakeDetailBinding;
public CakeDetailFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
fragmentCakeDetailBinding = FragmentCakeDetailBinding.inflate(inflater,container,false);
return fragmentCakeDetailBinding.getRoot();
}
}
Why is this happening?
private void getAllCakes(){
...
allCakeList.addAll(response.body());
adapter = new AllCakesAdapter(getActivity(),allCakeList);
fragmentCakeBinding.allCakeRecycler.setAdapter(adapter);
}
...
you're calling:
allCakeList.addAll(response.body());
every time without clearing your list out.
you have to clear that list:
allCakeList.clear();
allCakeList.addAll(response.body());
this is something you can easily determine yourself by just putting a breakpoint on your allCakeList to see what's inside it, if you haven't ever done this before, you should consider trying it out
Try the following and see if it solves your issue
CakeFragment.java
allCakeList.clear();
allCakeList.addAll(response.body());
//rest of the logic remains same
I tried to make a setListener on adapter to make something Action on the app. But the problem was when using this line of code to call setClickListener
adapter.setClickListener(this);
it gives me this error when using (this)
Required type: ItemClickListener
Provided: HomeImagesFragment
Here are my codes
Picassotest "Adapter for RecyclerView"
public class Picassotest extends RecyclerView.Adapter<Picassotest.ViewHolder> {
private String[] mData;
private Context context;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
public Picassotest(Context context, String[] data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
this.context = context;
}
// inflates the cell layout from xml when needed
#Override
#NonNull
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.images_list, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextView in each cell
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Picasso
.with(context)
.load(mData[position])
.fit() // to resize the image to imageView
.placeholder(R.drawable.loading_image) // load image
.transform(new PicassoRoundedTransformation(20, 0)) // Add radius to the images
.noFade()
.into(holder.mimageView);
}
// total number of cells
#Override
public int getItemCount() {
return mData.length;
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView mimageView;
ViewHolder(View itemView) {
super(itemView);
mimageView = itemView.findViewById(R.id.list_image);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
public String getItem(int id) {
return mData[id];
}
// allows clicks events to be caught
public void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
HomeImagesFragment "Fragment"
public class HomeImagesFragment extends Fragment {
private Picassotest adapter;
String[] chooseImages;
public HomeImagesFragment(String[] chooseImages) {
this.chooseImages = chooseImages;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.images_fragment_home, container, false);
/* ArrayList for chooseImages */
chooseImages = new String[]{
"https://quotess.cc/wp-content/uploads/2020/01/4688.jpg",
"https://whatt.cc/wp-content/uploads/2018/07/4443.jpg",
"https://quotess.cc/wp-content/uploads/2020/01/4688.jpg",
};
/* make new object and find the view "GridView" */
RecyclerView recyclerView = rootView.findViewById(R.id.recyclerview_image_choose);
// Calculate the items and auto-fit it on the screen
int mNoOfColumns = Utility.calculateNoOfColumns(getActivity(), 140);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), mNoOfColumns));
adapter = new Picassotest(getActivity(), chooseImages);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
return rootView;
}
public void onItemClick(int position) {
// get the image
String image = chooseImages[position];
Intent intent = new Intent(getActivity(), PicassoImageDisplayWallpaperAdapter.class);
intent.putExtra("imageUrl", image);
getActivity().startActivity(intent);
}
You need to create an interface like below code
interface ItemClickListener{
public void onItemClick(int position);
}
You need to implements ItemClickListener in your HomeImagesFragment
SAMPLE CODE
public class HomeImagesFragment extends Fragment implements ItemClickListener{
private Picassotest adapter;
String[] chooseImages;
public HomeImagesFragment(String[] chooseImages) {
this.chooseImages = chooseImages;
}
#Override
public void onItemClick(int position) {
// you will clikcked item position here
String image = chooseImages[position];
Intent intent = new Intent(getActivity(), PicassoImageDisplayWallpaperAdapter.class);
intent.putExtra("imageUrl", image);
getActivity().startActivity(intent);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.images_fragment_home, container, false);
/* ArrayList for chooseImages */
chooseImages = new String[]{
"https://quotess.cc/wp-content/uploads/2020/01/4688.jpg",
"https://whatt.cc/wp-content/uploads/2018/07/4443.jpg",
"https://quotess.cc/wp-content/uploads/2020/01/4688.jpg",
};
/* make new object and find the view "GridView" */
RecyclerView recyclerView = rootView.findViewById(R.id.recyclerview_image_choose);
// Calculate the items and auto-fit it on the screen
int mNoOfColumns = Utility.calculateNoOfColumns(getActivity(), 140);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), mNoOfColumns));
adapter = new Picassotest(getActivity(), chooseImages);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
return rootView;
}
public void onItemClick(int position) {
// get the image
String image = chooseImages[position];
Intent intent = new Intent(getActivity(), PicassoImageDisplayWallpaperAdapter.class);
intent.putExtra("imageUrl", image);
getActivity().startActivity(intent);
}
(Additional) Another way if you use Kotlin:
Sample Code
In Adapter class (Picassotest):
class Picassotest : RecyclerView.Adapter<Picassotest.ViewHolder>{
internal var itemClickListener: (Int) -> Unit = {}
inner class ViewHolder(itemView:View):RecyclerView.ViewHolder(itemView){
init{
itemView.setOnClickListener{
itemClickListener.invoke(adapterPosition)
}
}
}
}
In HomeImagesFragment:
class HomeImagesFragment{
adapter = new Picassotest(getActivity(), chooseImages)
adapter.itemClickListener = { position->
//TODO handle item on click here
}
}
I have Adapter in my project and few fragments where I populate fragments with celebrity names and date of birth as it is given in below image
I will like to call a different url to launch for each item
For First Item
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.stackoverflow.com")));
For Second Item
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com")));
and so on
Below is my Adapter Class
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<Model> mDataset;
private ImageLoader mImageLoader;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView nameText;
public TextView phoneText;
public NetworkImageView image;
#SuppressLint("WrongViewCast")
public ViewHolder(View v) {
super(v);
nameText = v.findViewById(R.id.name_text);
phoneText = v.findViewById(R.id.phone_text);
image = v.findViewById(R.id.imgAvatar);
image.setDefaultImageResId(R.mipmap.ic_launcher);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(),"Position: "+getAdapterPosition(), Toast.LENGTH_SHORT).show();
}
});
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(List<Model> myDataset, Context mCOntext) {
Log.d("TEST",myDataset.get(0).getName());
mDataset = myDataset;
mImageLoader = MySingleton.getInstance(mCOntext).getImageLoader();
}
// Create new views (invoked by the layout manager)
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view, parent, false);
// set the view's size, margins, paddings and layout parameters
ViewHolder vh = new ViewHolder(v);
return vh;
}
public interface ItemClickListener {
void onItemClick(View view, int position);
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
//holder.mTextView.setText(mDataset.get(position).getName());
Log.d("TEST","Printing Names onBindView Holder"+mDataset.get(position).getName());
holder.nameText.setText(mDataset.get(position).getName());
holder.phoneText.setText(mDataset.get(position).getPhone());
holder.image.setImageUrl(mDataset.get(position).getImage(),mImageLoader);
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.size();
}
}
and my Fragment is
public class english extends Fragment implements Response.Listener , Response.ErrorListener {
View view;
RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private Context context;
private List<Model> contactList = new ArrayList<>();
private String url ="https://api.androidhive.info/json/contacts.json";
Button btn;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.home_fragment,container,false);
context = getContext();
mLayoutManager = new GridLayoutManager(context,2);
mRecyclerView = (RecyclerView)view.findViewById(R.id.my_recycler_view);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(mLayoutManager);
getContactList();
return view;
}
private void getContactList(){
Log.d("TEST","Getting Contact list");
Controller.getInstance(context).makeNetworkCalls(Request.Method.GET,url,this,this);
}
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(context, "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
#Override
public void onResponse(Object response) {
Log.d("TEST","Got The response" +response);
if (response == null) {
Toast.makeText(context, "Couldn't fetch the contacts! Pleas try again.", Toast.LENGTH_LONG).show();
return;
}
List<Model> items = new Gson().fromJson(response.toString(), new TypeToken<List<Model>>(){}.getType());
contactList.addAll(items);
MyAdapter rcAdapter = new MyAdapter(contactList,context);
mRecyclerView.setAdapter(rcAdapter);
}
}
Please Help.
its Simple
First Create URL Array
in The Adapter Classs
ArrayList<String> UrlsToTran=new ArrayList<>();
in The Adapter Class Constructor
MyAdapter(Context mContext)
{
//Assing Context
//Assign The Urls
UrlsToTran.add("www.stackoverflow.com");
UrlsToTran.add("www.facebook.com");
//And Add More Values As U need
}
Then Add OnClick Listener
public void onBindViewHolder(ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
//holder.mTextView.setText(mDataset.get(position).getName());
Log.d("TEST","Printing Names onBindView
Holder"+mDataset.get(position).getName());
holder.nameText.setText(mDataset.get(position).getName());
holder.phoneText.setText(mDataset.get(position).getPhone());
holder.image.setImageUrl(mDataset.get(position).getImage(),mImageLoader);
holder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(UrlsToTran.get(position).toString())));
}
});
}
First, for every item in your adapter create an OnClickListener like this:
holder.image.setOnClickListener(v->{
});
Now Create an interface between the adapter and the fragment/activity that shows the list
public interface ModelListener {
void onModelClicked(Model model);
}
In your activity/fragment listen to an item click and send the intent
new ModelListener(){
public void onModelClicked(Model model){
startActivity(new Intent(.., model.getUrl()));
}
}
I have created a RecyclerView, and in the Adapter I am hoping to create a ClickListener. I want each item in the RecyclerView to send a unique response after click. In other words, a click is loading a different fragment for each specific RecyclerView item. Right now, the RecyclerView is not responding, as I have logged it and even added a Toast without any luck:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<LatestPoll> mDataSet;
int lastPosition = -1;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
// each data item is just a string in this case
protected TextView pollQuestion;
protected ImageView pollImage;
protected RelativeLayout individualItem;
public ViewHolder(View v) {
super(v);
pollQuestion = (TextView) v.findViewById(R.id.latest_item_question);
pollImage = (ImageView) v.findViewById(R.id.pollThumbNailImage);
individualItem = (RelativeLayout) v.findViewById(R.id.individual_item);
individualItem.setOnClickListener(this);
}
#Override
public void onClick(View v) {
v.getId();
int itemPosition = getLayoutPosition();
String item = String.valueOf(mDataSet.get(itemPosition));
Toast.makeText(getActivity().getApplicationContext(), item, Toast.LENGTH_LONG).show();
Log.v("TESTING", "ITEM CLICKED!");
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(ArrayList<LatestPoll> myDataset) {
mDataSet = myDataset;
}
// Create new views (invoked by the layout manager)
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.latest_item, parent, false);
// set the view's size, margins, paddings and layout parameters
return new ViewHolder(v);
}
// Replace the contents of a view (invoked by the layout manager)
//The OutOfBoundsException is pointing here
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Log.v("ON_BIND", "ON_BINDVIEWHOLDER CALLED");
LatestPoll latestPoll = mDataSet.get(position);
holder.pollQuestion.setText(latestPoll.getQuestion());
Picasso.with(getActivity())
.load(latestPoll.getPollImage())
.fit()
.placeholder(R.drawable.loading_spinnter_white)
.into(holder.pollImage);
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataSet.size();
}
}
private void onLoad() {
if (mFragmentListener != null) {
mFragmentListener.onFragmentLoaded();
}
}
public interface FragmentListener {
void onFragmentLoaded();
}
}
You need to set onclick listener to the parent layout inside the onBindViewHolder .
holder.parentID.setOnClickListener(mRecyclerViewListener);
In your View holder
parentID = iteView.findViewById(R.id.parent);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have an activity that has container that contain fragments and this fragment has other fragments.
Now I want this second or child fragment to access views in main activity, but it returns null pointer exception.
class:
public class ImageListFragment extends AbsListViewBaseFragment implements ObservableScrollViewCallbacks {
public static final int INDEX = 0;
android.support.design.widget.FloatingActionButton mFab;
#Bind(R.id.ic_call)
ImageView mIcCall;
#Bind(R.id.ic_email)
ImageView mIcEmail;
#Bind(R.id.ic_forum)
ImageView mIcForum;
FabToolbar mFabToolbar;
ObservableListView mObservableListView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fr_image_list, container, false);
listView = (ListView) rootView.findViewById(android.R.id.list);
((ListView) listView).setAdapter(new ImageAdapter(getActivity()));
final SubTaB mainActivity = (SubTaB)getActivity();
ButterKnife.bind(mainActivity);
//////////////// problem here
mFabToolbar = (FabToolbar) rootView.findViewById(R.id.fabtoolbar);
////////////////
getFragmentManager().findFragmentByTag("TAG");
// rootView.findViewById(R.id.fab);
mObservableListView = (ObservableListView)rootView.findViewById(android.R.id.list);
//
mObservableListView.setAdapter(this.listView.getAdapter());
mObservableListView.setScrollViewCallbacks(this);
mainActivity.mFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mainActivity.getApplicationContext(), "msg msg", Toast.LENGTH_LONG).show();
mainActivity.mFabToolbar.expandFab();
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
startImagePagerActivity(position);
}
});
return rootView;
}
#Override
public void onDestroy() {
super.onDestroy();
AnimateFirstDisplayListener.displayedImages.clear();
}
private static class ImageAdapter extends BaseAdapter {
private static final String[] IMAGE_URLS = Constants.IMAGES;
private LayoutInflater inflater;
private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
private DisplayImageOptions options;
ImageAdapter(Context context) {
inflater = LayoutInflater.from(context);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub) // تغيير الفيو قبل تحميل الصورة
.showImageForEmptyUri(R.drawable.ic_empty) // لما الصورة فاضية
.showImageOnFail(R.drawable.ic_error) // عند الفشل
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.displayer(new CircleBitmapDisplayer(Color.WHITE, 5))
.build();
}
#Override
public int getCount() {
return IMAGE_URLS.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = inflater.inflate(R.layout.item_list_image, parent, false);
holder = new ViewHolder();
holder.text = (TextView) view.findViewById(R.id.text);
holder.image = (ImageView) view.findViewById(R.id.image);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.text.setText("Item " + (position + 1));
ImageLoader.getInstance().displayImage(IMAGE_URLS[position], holder.image, options, animateFirstListener);
return view;
}
}
static class ViewHolder {
TextView text;
ImageView image;
}
#Override
public void onScrollChanged(int i, boolean b, boolean b1) {
}
#Override
public void onDownMotionEvent() {
}
#Override
public void onUpOrCancelMotionEvent(ScrollState scrollState) {
Log.d("","Scroll scroll scroll");
if (scrollState == ScrollState.UP) {
mFabToolbar.slideOutFab();
} else if (scrollState == ScrollState.DOWN) {
mFabToolbar.slideInFab();
}
}
#OnClick(R.id.fab)
void onFabClick() {
mFabToolbar.expandFab();
}
#OnClick(R.id.call)
void onClickCall() {
iconAnim(mIcCall);
}
#OnClick(R.id.ic_email)
void onClickEmail() {
iconAnim(mIcEmail);
}
#OnClick(R.id.ic_forum)
void onClickForum() {
iconAnim(mIcForum);
}
private void iconAnim(View icon) {
Animator iconAnim = ObjectAnimator.ofPropertyValuesHolder(
icon,
PropertyValuesHolder.ofFloat("scaleX", 1f, 1.5f, 1f),
PropertyValuesHolder.ofFloat("scaleY", 1f, 1.5f, 1f));
iconAnim.start();
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
}
It is not good practise to find and control a view in this way. Views can easily become detached from activities and cause unexpected exceptions.
You should rather look at using callbacks to communicate between fragments and activities if required. That way, it also keeps your code in the correct places - so the activity is the only one touching its own views and the fragment also only touches its own views. It merely tells the activity (via callbacks) that something has happened that the activity might want to know about. It also ensures that the fragments are completely self contained and can be easily reused.
You can read about how to implement callbacks here: http://developer.android.com/training/basics/fragments/communicating.html
Use EventBus to communicate between the activity and the fragment. riggarro suggestion is the correct way. But you can also able to update the base activity views using the EventBus.
For example we need to update a TextView text in a activity from the fragment, follow the steps.
First you need to add the following library as dependency to your project in build.gradle of your app.
compile 'de.greenrobot:eventbus:2.4.0'
First you need to create a Event Object class to communicate between the fragment and activity like below.
public class UpdateTextEvent {
private String sampleTextValue;
public UpdateTextEvent(String textValue) {
this.sampleTextValue = textValue;
}
public String getTextValue() {
return sampleTextValue;
}
}
You need to post a event to the event bus in the fragment to update the TextView in the activity.
public class TestingFragment extends Fragment{
private EventBus bus = EventBus.getDefault()
public TextingFragment(){}
public void onCreate(Bundle onSavedInstanceState){
super.onCreate(onSavedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.sample_activity, parent, false);
...
Button b1 = (Button) v.findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//trigger a update to the activity
bus.post(new UpdateTextEvent("testing"));
}
});
}
}
After that you need to register the bus with the callback of the event in the activity like below.
public class MainActivity extends Activity{
private EventBus bus = EventBus.getDefault();
private TextView textView;
#Override
public void onCreate(Bundle onSavedInstanceState){
super.onCreate(onSavedInstanceState);
....
// The textview going to be updated on posting the event
textView = (TextView) findViewById(R.id.text1);
bus.register(this);
}
public void onEvent(UpdateTextEvent event){
textView.setText(event.getTextValue());
}
}
In this above example the onEvent method will be called when you post a event from the fragment..
Hope it will help you.