Call OnClick with ImageView in other layout file - java

I have one Activity, which is MainActivity with a NavigationDrawer. So, when I click on my first item in my NavigationDrawer, I open a Fragment in MainActivity. In this Fragment, I inflate a layout with an ImageView. But when I click the ImageView, it does not work. Can you explain me why that's not work if it's possible? Thanks.
Here's the onClick implementation in my Fragment.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_stream, container, false);
mItemsContainer = (SwipeRefreshLayout) rootView.findViewById(R.id.container_items);
mItemsContainer.setOnRefreshListener(this);
//Pub perso
View rootViewx = inflater.inflate(R.layout.ad_item, container, false);
ImageView imgFavorite = rootViewx.findViewById(R.id.adviewperso);
imgFavorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = "MYURL";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
Toast.makeText(getActivity(),
"Pub appuyé !",
Toast.LENGTH_LONG).show();
}
});
//TEST2
CardView cardtest = rootViewx.findViewById(R.id.adCard);
cardtest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = "MYURL";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
Toast.makeText(getActivity(),
"Pub appuyé !",
Toast.LENGTH_LONG).show();
}
});
//TEST2
//Fin pub perso
mMessage = (TextView) rootView.findViewById(R.id.message);
mFabButton = (FloatingActionButton) rootView.findViewById(R.id.fabButton);
mFabButton.setImageResource(R.drawable.ic_action_new);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
itemsAdapter.setOnMoreButtonClickListener(new AdvancedItemListAdapter.OnItemMenuButtonClickListener() {
#Override
public void onItemClick(View v, Item obj, int actionId, int position) {
switch (actionId) {
case R.id.action_repost: {
if (obj.getFromUserId() != App.getInstance().getId()) {
if (obj.getRePostFromUserId() != App.getInstance().getId()) {
repost(position);
} else {
Toast.makeText(getActivity(), getActivity().getString(R.string.msg_not_make_repost), Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getActivity(), getActivity().getString(R.string.msg_not_make_repost), Toast.LENGTH_SHORT).show();
}
break;
}
case R.id.action_share: {
onPostShare(position);
break;
}
case R.id.action_report: {
report(position);
break;
}
case R.id.action_remove: {
remove(position);
break;
}
}
}
});
final GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 1);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(itemsAdapter);
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if(dy > 0) {
visibleItemCount = mLayoutManager.getChildCount();
totalItemCount = mLayoutManager.getItemCount();
pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();
if (!loadingMore) {
if ((visibleItemCount + pastVisiblesItems) >= totalItemCount && (viewMore) && !(mItemsContainer.isRefreshing())) {
loadingMore = true;
Log.e("...", "Last Item Wow !");
getItems();
}
}
}
}
});
mFabButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), NewItemActivity.class);
startActivityForResult(intent, STREAM_NEW_POST);
}
});
if (itemsAdapter.getItemCount() == 0) {
showMessage(getText(R.string.label_empty_list).toString());
} else {
hideMessage();
}
if (!restore) {
showMessage(getText(R.string.msg_loading_2).toString());
getItems();
}
return rootView;
}
And the layout containing adviewperso looks like the following.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:background="#F5F5F5"
android:clickable="true"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:id="#+id/adCard"
app:cardCornerRadius="#dimen/spacing_medium"
app:cardElevation="#dimen/spacing_xsmall"
app:cardUseCompatPadding="true">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="10dp">
<ImageView
android:layout_width="15dp"
android:layout_height="15dp"
android:tint="#color/sponsored"
android:src="#drawable/ic_sponsored"
android:visibility="visible" />
<TextView
android:id="#+id/adTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="3dp"
android:text="#string/label_sponsored"
android:textAppearance="#style/TextAppearance.AppCompat.Caption"
android:textColor="#color/sponsored"
android:textStyle="normal"
android:visibility="visible" />
</LinearLayout>
<RelativeLayout
android:minHeight="64dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:paddingBottom="10dp"
android:paddingTop="10dp">
<ImageView
android:id="#+id/adviewperso"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:srcCompat="#drawable/pub" />
<com.google.android.gms.ads.NativeExpressAdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adUnitId="#string/banner_ad_unit_id"
android:visibility="invisible"
ads:adSize="320x150">
</com.google.android.gms.ads.NativeExpressAdView>
</RelativeLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
I do not have any errors when I compile or when I run my app.

I would suggest two things. Make the ImageView clickable from the layout and I think the AdView is overlapping the ImageView which is making it not clickable.
So the views under the RelativeLayout should look like the following.
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:minHeight="64dp"
android:paddingBottom="10dp"
android:paddingTop="10dp">
<ImageView
android:id="#+id/adviewperso"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
ads:srcCompat="#drawable/ic_add" />
<com.google.android.gms.ads.NativeExpressAdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/adviewperso"
android:visibility="invisible"
ads:adSize="320x150"
ads:adUnitId="#string/banner_ad_unit_id"/>
</RelativeLayout>
Update
You are returning rootView from your onCreateView. You cannot inflate multiple layouts in a single Fragment. So the layout you are inflating using View rootViewx = inflater.inflate(R.layout.ad_item, container, false); will not have any effect if you are not returning the same layout from onCreateView.
I hope you have the ImageView in your fragment_stream layout or it includes the ad_item layout. So if the ad_item layout is included in your fragment_stream layout, then you can get the view id associated with the layout easily without having inflating it separately.
If you have two Fragment, then you need two separate Fragment class where you inflate ad_item and fragment_stream separately. And then, you join them together using another Fragment as a holder of these two fragments.

Related

Slide image with recyclerview in full screen android

I have created a wallpaper app where I'm loading images from the firebase database in recyclerview. When I click on recyclerview item(image) that item's image URL is sent to the next activity and then that URL is loaded into imageView using glide.
I want to change this to something like Image-Slider. By clicking on the recyclerView item I want to show that image in full screen and slide from left or right(next or previous). But I don't know how to do that.
Here is my code.
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3));
adapter = new FeaturedAdapter(list);
recyclerView.setAdapter(adapter);
databaseReference = FirebaseDatabase.getInstance().getReference().child("Wallpaper All");
Query query = databaseReference.orderByChild("dark").equalTo(true);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
list.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
FeaturedModel model = dataSnapshot1.getValue(FeaturedModel.class);
list.add(model);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.e("TAG_DATABASE_ERROR", databaseError.getMessage());
}
});
FeaturedAdapter.java
public class FeaturedAdapter extends RecyclerView.Adapter<FeaturedAdapter.ViewHolder> {
private List<FeaturedModel> featuredModels;
public FeaturedAdapter(List<FeaturedModel> featuredModels) {
this.featuredModels = featuredModels;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_image, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.setData(featuredModels.get(position).getImageLink()
, position,
featuredModels.get(position).isPremium());
}
#Override
public int getItemCount() {
return featuredModels.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private ImageView imageView;
private ImageView premiumImage;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageview);
premiumImage = itemView.findViewById(R.id.premium);
}
private void setData(final String url, final int position, boolean premium) {
Glide.with(itemView.getContext().getApplicationContext()).load(url).into(imageView);
if (premium) {
premiumImage.setVisibility(View.VISIBLE);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent setIntent = new Intent(itemView.getContext(), PremiumViewActivity.class);
//setIntent.putExtra("title", url);
setIntent.putExtra("images", featuredModels.get(getAdapterPosition()).getImageLink());
setIntent.putExtra("id", featuredModels.get(position).getId());
itemView.getContext().startActivity(setIntent);
}
});
} else {
premiumImage.setVisibility(View.GONE);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent setIntent = new Intent(itemView.getContext(), ViewActivity.class);
//setIntent.putExtra("title", url);
setIntent.putExtra("images", featuredModels.get(getAdapterPosition()).getImageLink());
setIntent.putExtra("id", featuredModels.get(position).getId());
itemView.getContext().startActivity(setIntent);
}
});
}
}
}
}
ViewActivity
Random rnd = new Random();
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
relativeLayout.setBackgroundColor(color);
Glide.with(this)
.load(getIntent().getStringExtra("images"))
.timeout(6000)
.listener(new RequestListener<Drawable>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
relativeLayout.setBackgroundColor(Color.TRANSPARENT);
return false;
}
#Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
relativeLayout.setBackgroundColor(Color.TRANSPARENT);
return false;
}
})
.into(imageView);
setBackgroundWall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setBackgroundImage();
}
});
}
private void setBackgroundImage() {
Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
WallpaperManager manager = WallpaperManager.getInstance(getApplicationContext());
try {
manager.setBitmap(bitmap);
Toasty.success(getApplicationContext(), "Set Wallpaper Successfully", Toast.LENGTH_SHORT, true).show();
} catch (IOException e) {
Toasty.warning(this, "Wallpaper not load yet!", Toast.LENGTH_SHORT, true).show();
}
}
activity_view.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activity.PremiumViewActivity">
<ImageView
android:id="#+id/viewImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:contentDescription="#null"
android:scaleType="centerCrop"
android:src="#00BCD4"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent" />
<com.airbnb.lottie.LottieAnimationView
android:id="#+id/lottieSuccess"
android:layout_width="180dp"
android:layout_height="180dp"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:lottie_fileName="checked.json" />
<RelativeLayout
android:id="#+id/wallpaper_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent">
<ImageButton
android:id="#+id/saveImage"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="20dp"
android:background="#drawable/set_as_wallpaper_btn"
android:contentDescription="#null"
android:src="#drawable/save" />
<Button
android:id="#+id/setWallpaper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="4dp"
android:layout_marginEnd="8dp"
android:background="#drawable/set_as_wallpaper_btn"
android:minWidth="230dp"
android:text="Set as wallpaper"
android:textColor="#000"
android:textStyle="bold" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:orientation="horizontal">
<CheckBox
android:id="#+id/favoritesBtn_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="6dp"
android:button="#drawable/favourite_checkbox_selector" />
<ImageButton
android:id="#+id/shareBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="6dp"
android:background="#drawable/share"
android:contentDescription="#null" />
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:id="#+id/ads_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="12dp"
android:visibility="visible"
app:layout_constraintBottom_toBottomOf="parent">
<Button
android:id="#+id/watch_ads"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:background="#drawable/set_as_wallpaper_btn"
android:drawableStart="#drawable/advertizing"
android:paddingStart="50dp"
android:paddingEnd="50dp"
android:stateListAnimator="#null"
android:text="Watch Video Ad"
android:textColor="#000"
android:textStyle="bold" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/watch_ads">
<Button
android:id="#+id/unlock_withCoins"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginStart="20dp"
android:layout_marginTop="15dp"
android:layout_marginEnd="20dp"
android:background="#drawable/set_as_wallpaper_btn"
android:drawableStart="#drawable/diamond"
android:paddingStart="50dp"
android:paddingEnd="50dp"
android:stateListAnimator="#null"
android:text="Unlock with diamonds"
android:textColor="#000"
android:textStyle="bold" />
<TextView
android:id="#+id/diamonds_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:gravity="center"
android:text="Total Diamonds: 0"
android:textSize="10sp"
android:textStyle="bold" />
</RelativeLayout>
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
custom_image.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:background="#fff"
app:cardCornerRadius="10dp"
app:cardUseCompatPadding="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="#null"
android:scaleType="centerCrop"
android:src="#color/colorPrimary" />
<ImageView
android:id="#+id/premium"
android:contentDescription="#null"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_margin="10dp"
app:srcCompat="#drawable/diamond" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
Structure
MainActivity
|
| //Click button to open
|
FragActivity
|
| //FrameLayout
|
Fragment
|
| //here is the recyclerView
| //Open new Activity to view image
ViewActivity
Screen Recording
This can be solved by using ViewPager or ViewPager2 in Android
First create an Adapter
ImageSwiperAdapter2.java
public class ImageSwiperAdapter2 extends RecyclerView.Adapter<ImageSwiperAdapter2.ImageSwiper> {
private List<FeaturedModel> list;
private Context context;
public ImageSwiperAdapter2(List<FeaturedModel> list, Context context) {
this.list = list;
this.context = context;
}
#NonNull
#Override
public ImageSwiper onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.slidingimages,
parent, false);
return new ImageSwiper(view);
}
#Override
public void onBindViewHolder(#NonNull final ImageSwiper holder, int position) {
Random rnd = new Random();
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
holder.relativeLayout.setBackgroundColor(color);
Glide.with(context.getApplicationContext())
.load(list.get(position).getImageLink())
.listener(new RequestListener<Drawable>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
holder.relativeLayout.setBackgroundColor(Color.TRANSPARENT);
return false;
}
#Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
holder.relativeLayout.setBackgroundColor(Color.TRANSPARENT);
return false;
}
})
.into(holder.imageView);
}
#Override
public int getItemCount() {
return list.size();
}
class ImageSwiper extends RecyclerView.ViewHolder {
private ImageView imageView;
public ImageSwiper(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
}
}
}
In ViewActivity/SwiperActivity.java
public class SwiperActivity extends AppCompatActivity {
private ViewPager2 viewPager;
private List<FeaturedModel> list;
private ImageSwiperAdapter2 adapter2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swiper);
viewPager = findViewById(R.id.view_pager);
final int pos = getIntent().getIntExtra("pos", 0);
Singleton singleton = Singleton.getInstance();
list = new ArrayList<>();
list = singleton.getListSin();
adapter2 = new ImageSwiperAdapter2(list, this);
viewPager.setAdapter(adapter2);
viewPager.setCurrentItem(pos);
viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
Toast.makeText(SwiperActivity.this, "Selected: " + position, Toast.LENGTH_SHORT).show();
}
#Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
}
});
}
}
You can pass the list and clicked item position in FeaturedAdapter.
In your FeaturedAdapter's setData method
private void setData(final String url, final int position, boolean premium) {
Glide.with(itemView.getContext().getApplicationContext()).load(url).into(imageView);
final Singleton a = Singleton.getInstance();
a.setListSin(featuredModels);
if (premium) {
premiumImage.setVisibility(View.VISIBLE);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent setIntent = new Intent(itemView.getContext(), SwiperActivity.class);
setIntent.putExtra("pos", position);
itemView.getContext().startActivity(setIntent);
CustomIntent.customType(itemView.getContext(), "fadein-to-fadeout");
}
});
} else {
premiumImage.setVisibility(View.GONE);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent setIntent = new Intent(itemView.getContext(), SwiperActivity.class);
setIntent.putExtra("pos", position);
itemView.getContext().startActivity(setIntent);
CustomIntent.customType(itemView.getContext(), "fadein-to-fadeout");
}
});
}
}
slidingimages.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:contentDescription="#null"
android:scaleType="centerCrop" />
</RelativeLayout>
activity_swiper.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SwiperActivity">
<androidx.viewpager2.widget.ViewPager2
android:orientation="horizontal"
android:id="#+id/view_pager"
android:layoutDirection="inherit"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Since the ViewActivity must show all the images(when slided) it must contain the adapter with the set of image urls.
Instead of using an ImageView, use a RecyclerView in the ViewActivity and attach the adapter. In your code, do the following to make the recycler view horizontal and add slide functionality.
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.HORIZONTAL,false));
SnapHelper snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);
Few Days ago, I had been looking for similar requirement for showing slid-able image View.
This situation can be solved using ViewPager in Android.
You can use following Tutorials for building such Slide Image View using ViewPager
Java Resources
Blog Tutorial
Video Tutorial
Kotlin Resources
Video Tutorial

RecyclerView not replacing detail pane with fragment on item click

Everytime I click a recycler view item on a tablet, it opens an activity rather than replacing the detail pane with a fragment.
The following line of code is what I use to detect wheter the detail pane is present:
mTwoPane = Objects.requireNonNull(getActivity()).findViewById(R.id.detail_container) != null;
Any ideas on the correct location to put this line of code?
activity XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.widget.Toolbar
android:id="#+id/masterToolbar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
>
<LinearLayout
android:id="#+id/singleline_text_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="vertical">
<TextView
android:id="#+id/md_toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#android:style/TextAppearance.Material.Widget.ActionBar.Title"/>
</LinearLayout>
</android.widget.Toolbar>
<RelativeLayout
android:id="#+id/master_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
sw600dp activity XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.widget.Toolbar
android:id="#+id/masterToolbar"
android:layout_width="0dp"
android:layout_height="?actionBarSize"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toStartOf="#+id/detailBackgroundToolbar"
app:layout_constraintHorizontal_weight="2"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:id="#+id/singleline_text_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="vertical">
<TextView
android:id="#+id/md_toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#android:style/TextAppearance.Material.Widget.ActionBar.Title"/>
</LinearLayout>
</android.widget.Toolbar>
<RelativeLayout
android:id="#+id/master_container"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintHorizontal_weight="2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toStartOf="#+id/divider"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#+id/masterToolbar" />
<View
android:id="#+id/divider"
android:layout_width="1dp"
android:layout_height="0dp"
android:background="?attr/dividerColor"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="#+id/masterToolbar"
app:layout_constraintTop_toBottomOf="#+id/masterToolbar" />
<android.widget.Toolbar
android:id="#+id/detailBackgroundToolbar"
android:layout_width="0dp"
android:layout_height="?actionBarSize"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_weight="3"
app:layout_constraintStart_toEndOf="#+id/masterToolbar"
app:layout_constraintTop_toTopOf="parent" />
<android.support.v7.widget.CardView
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_margin="4dp"
app:cardCornerRadius="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/divider"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintWidth_percent="0.5">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/toolbar_dualline"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<FrameLayout
android:id="#+id/detail_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</android.support.v7.widget.CardView>
<View
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/divider"
app:layout_constraintTop_toBottomOf="#+id/detailBackgroundToolbar" />
</android.support.constraint.ConstraintLayout>
Fragment class
public class MyFragment extends Fragment {
public MyFragment() {}
List<Product> wcList;
RecyclerView mRecyclerView;
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet device.
*/
public boolean mTwoPane;
public static MyFragment newInstance() {
return new MyFragment();
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
mTwoPane = Objects.requireNonNull(getActivity()).findViewById(R.id.detail_container) != null;
mRecyclerView = view.findViewById(R.id.recyclerView_list);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
mRecyclerView.addItemDecoration(new DividerItemDecoration(Objects.requireNonNull(getContext()), LinearLayout.VERTICAL));
myList = new ArrayList<>();
String[] items = getResources().getStringArray(R.array.product_names);
String[] itemDescriptions = getResources().getStringArray(R.array.product_descriptions);
for (int n = 0; n < items.length; n++){
Product desserts = new Product();
desserts.setProductName(items[n]);
wdessertsc.setProductDescriptions(itemDescriptions[n]);
myList.add(desserts);
}
MyListAdapter listAdapter = new MyListAdapter(getActivity(), myList);
mRecyclerView.setAdapter(listAdapter);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
mTwoPane = Objects.requireNonNull(getActivity()).findViewById(R.id.detail_container) != null;
super.onActivityCreated(savedInstanceState);
}
}
Adapter class
public class MyListAdapter extends RecyclerView.Adapter<MyListAdapter.MyViewHolder> {
public boolean mTwoPane;
private Context mCtx;
private List<Product> myList;
public MyListAdapter(Context mCtx, List<Product> myList) {
this.mCtx = mCtx;
this.myList = myList;
}
#NonNull
#Override
public MyListAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.listitem_dualline, parent,false);
return new MyListAdapter.MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MyListAdapter.MyViewHolder holder, final int position) {
Log.d(TAG, "onBindViewHolder: called.");
final Product product = myList.get(holder.getAdapterPosition());
holder.textviewTitle.setText(product.getProductName());
holder.textviewSubtitle.setText(product.getPRoductDescription());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Fragment newFragment;
if (product.getStationName().equals(v.getResources().getString(R.string.product_1))) {
newFragment = new FragmentProduct1();
} else {
newFragment = new FragmentProdcut2();
}
MyActivity activity = (MyActivity) v.getContext();
FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.detail_container, newFragment);
transaction.commit();
} else {
Intent intent;
if (product.getStationName().equals(v.getResources().getString(R.string.product_1))) {
intent = new Intent(v.getContext(), Product1Activity.class);
} else {
intent = new Intent(v.getContext(), Product2Activity.class);
}
mCtx.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return myList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
RelativeLayout relativeLayout;
TextView textviewTitle, textviewSubtitle;
StationViewHolder(View itemView) {
super(itemView);
mTwoPane = itemView.findViewById(R.id.detail_container) != null;
relativeLayout = itemView.findViewById(R.id.listitem_relativelayout);
textviewTitle = itemView.findViewById(R.id.listitem_title);
textviewSubtitle = itemView.findViewById(R.id.listitem_subtitle);
}
}
}
This line mTwoPane = itemView.findViewById(R.id.detail_container) != null; from your view holder will always be false.
Why?
Because, your detail_container is not part of your view holder's item container, so itemView will always return null for your view. instead pass your boolean flag from your fragment to your adapter !
I think you are checking item two pan with recyclerview item xml
mTwoPane = itemView.findViewById(R.id.detail_container) != null;
That you can check while constructing recyclerview adapter and save it from the activity content view itself.

Why does Input from an AlertDialog not show in RecyclerView?

I want to take input from an AlertDialog box and set it to 2 variables then use those variables as an argument to make a list using recyclerview.
With the code in its this state it brings up the dialogbox and when i enter information and press "add" nothing shows onto the screen.
Here is my Java file:
public class tab1Expenses extends Fragment {
List<ExRow> expenseList = new ArrayList<>();
RecyclerView recyclerView;
ExpensesAdapter mAdapter;
Button btnEx;
EditText txtExName;
EditText txtExAmount;
public void expenseData() {
ExRow exs = new ExRow(txtExNa, txtExAm);
expenseList.add(exs);
mAdapter.notifyDataSetChanged();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.tab1expense, container, false);
btnEx = (Button) rootView.findViewById(R.id.btnEx);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
mAdapter = new ExpensesAdapter(expenseList);
RecyclerView.LayoutManager mLayoutManager = new RecyclerView.LayoutManager() {
#Override
public RecyclerView.LayoutParams generateDefaultLayoutParams() {
return null;
}
};
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
btnEx.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View view = LayoutInflater.from(tab1Expenses.this.getActivity())
.inflate(R.layout.add_ex, null);
txtExName = (EditText) view.findViewById(R.id.exName);
txtExAmount = (EditText) view.findViewById(R.id.exAmount);
AlertDialog.Builder add = new AlertDialog.Builder(tab1Expenses.this.getActivity());
add.setCancelable(true)
.setTitle("Enter Expense:")
.setView(view)
.setPositiveButton("Add",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
expenseData();
}
});
Dialog dialog = add.create();
dialog.show();
}
});
return rootView;
}
}
Here is the related XML file:
<Button
android:text="Add Expense"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnEx"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:width="800dp"
android:textAppearance="#style/TextAppearance.AppCompat.Widget.Switch"
android:background="#android:color/black"
android:textColor="#android:color/holo_green_light"
android:textColorLink="#android:color/holo_green_light" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="17dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
</LinearLayout>
</ScrollView>
And the XML file for adding inputs:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/background_light">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/exName"
android:textColorLink="#android:color/holo_green_light"
android:textColorHighlight="#android:color/holo_green_light"
android:editable="false"
android:hint="Expense Name" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/exAmount"
android:textColorLink="#android:color/holo_green_light"
android:textColorHighlight="#android:color/holo_green_light"
android:hint="Expense Amount" />
</LinearLayout>
You need to get the reference for txtExName and txtExAmount from view not rootview. So from your latest code remove these lines
txtExName = (EditText) rootView.findViewById(R.id.exName);
txtExAmount = (EditText) rootView.findViewById(R.id.exAmount);
and add these lines on same spot.
txtExName = (EditText) view.findViewById(R.id.exName);
txtExAmount = (EditText) view.findViewById(R.id.exAmount);
OK, so as I can see the issue is due to it not being able to find EditText named txtExName, and txtExAmount. So,
cut these two lines:
recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
txtExName = (EditText) rootView.findViewById(R.id.exName); //<---This one
txtExAmount = (EditText) rootView.findViewById(R.id.exAmount); // <--And this one
and replace them with these:
View view = LayoutInflater.from(tab1Expenses.this.getActivity())
.inflate(R.layout.add_ex, null);
txtExName = (EditText) view.findViewById(R.id.exName);
txtExAmount = (EditText) view.findViewById(R.id.exAmount);
Hope it helps.
where are yours EditTexts in you XML file posted?
Probably it's return null because it's not finding any EditText:
String txtExNa = (txtExAmount.getText()).toString(); //here is crash, i think
Sorry my english and I hope this help!
OK so this may be final answer. I will try to cover up everything you are trying to do.
//This is tab1expense.xml (Without toolbar)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:text="Add Expense"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnEx"
android:textAppearance="#style/TextAppearance.AppCompat.Widget.Switch"
android:background="#android:color/black"
android:textColor="#android:color/holo_green_light"
android:textColorLink="#android:color/holo_green_light" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
</LinearLayout>
//This is add_ex.xml (Used in popup)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/background_light">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/exName"
android:textColorLink="#android:color/holo_green_light"
android:textColorHighlight="#android:color/holo_green_light"
android:editable="false"
android:hint="Expense Name" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/exAmount"
android:textColorLink="#android:color/holo_green_light"
android:textColorHighlight="#android:color/holo_green_light"
android:hint="Expense Amount" />
</LinearLayout>
//Now a Class called ExRow.java
public class ExRow{
String str_txtExNa,str_txtExAm;
ExRow(String str_txtExNa, String str_txtExAm){
this.str_txtExNa=str_txtExNa;
this.str_txtExAm=str_txtExAm;
}
public String getNa()
{
return str_txtExNa;
}
public String getAm()
{
return str_txtExAm;
}
}
//Now your tab1Expenses.java
public class tab1Expenses extends Fragment {
ArrayList<ExRow> expenseList = new ArrayList<>();
RecyclerView recyclerView;
ExpensesAdapter mAdapter;
Button btnEx;
EditText txtExName;
EditText txtExAmount;
public void expenseData(String txtExNa,String txtExAm) {
ExRow exs = new ExRow(txtExNa, txtExAm);
expenseList.add(exs);
mAdapter.notifyDataSetChanged();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.tab1expense, container, false);
btnEx = (Button) rootView.findViewById(R.id.btnEx);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
mAdapter = new ExpensesAdapter(expenseList);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
btnEx.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View view = LayoutInflater.from(tab1Expenses.this.getActivity())
.inflate(R.layout.add_ex, null);
txtExName = (EditText) view.findViewById(R.id.exName);
txtExAmount = (EditText) view.findViewById(R.id.exAmount);
AlertDialog.Builder add = new AlertDialog.Builder(tab1Expenses.this.getActivity());
add.setCancelable(true)
.setTitle("Enter Expense:")
.setView(view)
.setPositiveButton("Add",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
expenseData(txtExName.getText().toString(),txtExAmount`enter code here`.getText().toString() );
}
});
Dialog dialog = add.create();
dialog.show();
}
});
return rootView;
}
}
//row_item_view.xml (Layout for row View of RecyclerView)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/row_name"
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center"/>
<TextView
android:id="#+id/row_amount"
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center"/>
</LinearLayout>
//Finally the Adapter Class i.e, ExpensesAdapter.java
public class ExpensesAdapter extends RecyclerView.Adapter<ExpensesAdapter.ViewHolder> {
private ArrayList<ExRow> expenseList;
// Constructor of the class
public ExpensesAdapter(ArrayList<ExRow> expenseList) {
this.expenseList = expenseList;
}
// get the size of the list
#Override
public int getItemCount() {
return expenseList == null ? 0 : expenseList.size();
}
// specify the row layout file
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item_view, parent, false);
ViewHolder myViewHolder = new ViewHolder(view);
return myViewHolder;
}
// load data in each row element
#Override
public void onBindViewHolder(final ViewHolder holder, final int listPosition) {
holder.row_name.setText(expenseList.get(listPosition).getNa());
holder.row_amount.setText(expenseList.get(listPosition).getAm());
}
// Static inner class to initialize the views of rows
static class ViewHolder extends RecyclerView.ViewHolder{
public TextView row_name,row_amount;
public ViewHolder(View itemView) {
super(itemView);
row_name = (TextView) itemView.findViewById(R.id.row_name);
row_amount = (TextView) itemView.findViewById(R.id.row_amount);
}
}
}
Hope this finally solves the issue.

how to set text to text view based on the selection of item in dialogfragment and value of text in main activity, is it possible?

Here I am trying to set text to a textview in my activity.
The text is set to the text view based on the text of the text view in my activity and the selected item in the custom dialog fragment.
The dialog fragment consists of recycler view and a button.when item is selected from the fragment and text of textview of my activity, and with both cases settext to the textview. I tried different code but I not getting how to achieve it anyone give me solution for it. is there a way to get it.
by using value of text and selected item, adding my math and condition to it. settext to the textview. I am beginner to coding can any one help me please I'm trying from 5 days to achieve it. please help me thanks in advance
activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_main" tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="YOUR DAILY TARGET"
android:layout_gravity="center"
android:id="#+id/textView7"
android:layout_marginTop="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:layout_gravity="center"
android:id="#+id/res"
android:layout_marginTop="20dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Select a glass"
android:layout_marginLeft="10dp"
android:id="#+id/textView6"
android:layout_gravity="center" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="65dp"
android:src="#android:drawable/ic_input_add" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="70dp"
android:layout_height="70dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="0"
android:background="#drawable/circle"
android:gravity="center"
android:id="#+id/glasses"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="31dp"
android:layout_marginEnd="31dp"
android:layout_marginBottom="121dp" />
</RelativeLayout>
</LinearLayout>
MainActivity:
public class MainActivity extends AppCompatActivity {
private Listen selectedListen;
protected void setDataFromMyDialog(Listen listen) {
this.selectedListen = listen;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (isFirstRun) {
//show start activity
startActivity(new Intent(MainActivity.this, Page.class));
Toast.makeText(MainActivity.this, "First Run", Toast.LENGTH_LONG)
.show();
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("isFirstRun", false).commit();
TextView textView = (TextView)findViewById(R.id.res);
Intent r = getIntent();
double res = r.getDoubleExtra("res", 0);
textView.setText(+res + "L"); // with this text value
double ram = Double.parseDouble(textView.getText().toString());
TextView gls = (TextView) findViewById(R.id.glasses);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DiaFragment df = new DiaFragment();
df.show(MainActivity.this.getSupportFragmentManager(), "Frag");
}
});
}
with the text of textview above and selected item in my dialog fragment by using both the values the set text of TextView glasses.is it possible to get like this
DiaFrag:
public class DiaFragment extends DialogFragment {
ListAdapter listAdapter;
public DiaFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_dialog, container, false);
setCancelable(false);
Button ok = (Button) v.findViewById(R.id.submit);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(),LinearLayoutManager.HORIZONTAL,false);
RecyclerView recyclerView = (RecyclerView) v.findViewById(R.id.list);
listAdapter = new ListAdapter(getContext(),getData());
recyclerView.setAdapter(listAdapter);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity)getActivity()).setDataFromMyDialog(listAdapter.getSelectedData());
dismiss();
}
});
return v;
}
public static List<Listen> getData()
{
List<Listen> data = new ArrayList<>();
int[] images = {R.drawable.bottle,R.drawable.lotion,R.drawable.soap,R.drawable.soda,R.drawable.sodaa};
String[] texts = {"250ml","300ml","500ml","750ml","1ltr"};
for (int i=0;i<texts.length && i<images.length;i++){
Listen current = new Listen();
current.img = images[i];
current.text= texts[i];
data.add(current);
}
return data;
}
}

setOnClickListener not firing with custom adapter and custom ListView

I've been spending a few hours on a problem and I still can't figure it out. The setOnClickListener in HotelOverviewFragment is not firing when I click an item in my ListView. However, the setOnClickListener does work from my custom adapter (NowArrayAdapter).
My question is: why the setOnClickListener not working in HotelOverviewFragment (Class where the ListView is shown)?
Here's a list of what I've tried:
Setting android:focusable="false", android:focusableInTouchMode="false", android:descendantFocusability="blocksDescendants" in the hotel_row_layout.xml and fragment_hotel_overview.xml.
Setting android:clickable on true and false. Both didn't work.
Changing from BaseAdapter implementation to arrayAdapter.
I tried different listeners in HotelOverviewFragment: setOnClickListener, setOnItemClickListener, setOnItemSelectedListener and setOnTouchListener. Unfortunately, none of those worked for me.
Here's my code:
Custom adapter
public class NowArrayAdapter extends ArrayAdapter<String> {
private Context context;
private ArrayList<String> values;
private Typeface typeface;
private static Hashtable fontCache = new Hashtable();
private LayoutInflater inflater;
private TextView item;
public NowArrayAdapter(Context context, ArrayList<String> commandsList) {
super(context, R.layout.hotel_row_layout, commandsList);
this.context = context;
values = new ArrayList<String>();
values.addAll(commandsList);
typeface = getTypeface(this.context, "fonts/Roboto-Light.ttf");
inflater = LayoutInflater.from(this.context);
}
static Typeface getTypeface(Context context, String font) {
Typeface typeface = (Typeface)fontCache.get(font);
if (typeface == null) {
typeface = Typeface.createFromAsset(context.getAssets(), font);
fontCache.put(font, typeface);
}
return typeface;
}
public View getView(int position, View convertView, ViewGroup parent) {
String myText = getItem(position);
if(convertView == null) {
convertView = inflater.inflate(R.layout.hotel_row_layout, parent, false);
item = (TextView) convertView.findViewById(R.id.maps_button);
item.setTypeface(typeface);
convertView.setTag(item);
} else {
item = (TextView) convertView.getTag();
}
item.setText(myText);
//myListItem.descText.setTextSize(14);
convertView.setOnClickListener(new View.OnClickListener() {
// WORKS!
#Override
public void onClick(View view) {
Log.d("click", "Don't look at me!");
}
});
return convertView;
}
}
Fragment
public class HotelOverviewFragment extends Fragment {
private static Hashtable fontCache = new Hashtable();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_hotel_overview, container, false);
ListView list = (ListView) v.findViewById(android.R.id.list);
// Set up listview and buttons
setUp(v, list);
// Inflate the layout for this fragment
return v;
}
static Typeface getTypeface(Context context, String font) {
Typeface typeface = (Typeface)fontCache.get(font);
if (typeface == null) {
typeface = Typeface.createFromAsset(context.getAssets(), font);
fontCache.put(font, typeface);
}
return typeface;
}
public void setUp(View v, ListView l){
TextView address = (TextView) v.findViewById(R.id.content);
TextView header = (TextView) v.findViewById(R.id.header);
TextView hotelName = (TextView) v.findViewById(R.id.hotelName);
Typeface typeface = getTypeface(getActivity(), "fonts/Roboto-Light.ttf");
address.setText("some street \nZipCode, City \nCountry \nEmail \nphoneNumber");
address.setTypeface(typeface);
header.setText("Hotel info");
header.setTypeface(typeface);
header.setTextSize(20);
hotelName.setText("Hotel name");
hotelName.setTypeface(typeface);
// Set up button
ArrayList<String> n = new ArrayList<String>();
n.add(0, "More info");
// Show button
NowArrayAdapter adapter = new NowArrayAdapter(getActivity(), n);
l.setAdapter(adapter);
// THIS IS THE STUFF I'VE BEEN TRYING
try {
l.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("click", "Success");
}
});
l.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("click", "Success");
}
});
l.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d("click", "Success");
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
l.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("click", "Success");
return false;
}
});
}catch (Exception e){
Log.d("click", e + "");
}
}
}
Layout xml of HotelOverviewFragment
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context="com.example"
android:background="#ffebebeb">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="fill_parent"
android:layout_height="200dp"
android:src="#drawable/banner"
android:id="#+id/hotelBanner"
android:layout_gravity="top"
android:adjustViewBounds="false"
android:scaleType="fitXY" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Hotelname"
android:id="#+id/hotelName"
android:gravity="center"
android:textSize="40dp"
android:layout_alignBottom="#+id/hotelBanner"
android:layout_alignParentRight="false"
android:layout_alignParentLeft="false"
android:textColor="#ffc4c4c4"
android:layout_marginBottom="5dp" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="0dp"
android:background="#drawable/header_card">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/header"
android:layout_gravity="center_vertical"
android:layout_width="wrap_content"
android:layout_weight="1"
android:textColor="#android:color/primary_text_light"
android:layout_height="wrap_content"
android:text="Header"
android:layout_toRightOf="#+id/headerImage"
android:layout_centerVertical="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/headerImage"
android:src="#drawable/ic_action_live_help"
android:layout_centerVertical="true" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="0dp"
android:layout_marginBottom="0dp"
android:background="#drawable/content_card">
<TextView
android:id="#+id/content"
android:layout_gravity="left|center_vertical"
android:layout_width="fill_parent"
android:layout_weight="1"
android:textColor="#android:color/primary_text_light"
android:layout_height="wrap_content"
android:text="Content"
/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp">
<ListView android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:clickable="true"/>
</LinearLayout>
</LinearLayout>
</ScrollView>
The custom xml for a listview item
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:layout_marginTop="4dp"
android:layout_marginBottom="4dp"
android:background="#drawable/content_card">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/maps_button"
android:layout_gravity="left|center_vertical"
android:layout_width="wrap_content"
android:layout_weight="1"
android:textColor="#android:color/primary_text_light"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true" />
<ImageView
android:src="#drawable/ic_action_arrow_right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:layout_alignParentTop="false"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="false"
android:layout_centerVertical="true"
/>
</RelativeLayout>
</LinearLayout>
Thanks in advance.
Thanks to Daniel Nugent's suggestion I got it working. Removing the convertView.setOnClickListener() is part of the answer. I think it was blocking the other listeners in the HotelOverviewFragment.
My next mistake was that I used setOnClickListener on a ListView for testing.
setOnClickListener should be used for buttons not ListViews.
So after removing setOnClickListener all the other listeners started working.
Thanks for your time.

Categories