I have a custom dialog that has a ViewPager inside of it, when the dialog shows the ViewPager is just blank, not progressing on swipe or when pressing the "Next" button I implemented. I tried slightly altering my code and it didn't work. I saw several posts like this, but none of their solutions worked. PS if some things don't make sense or have mismatched names then that's because I renamed/removed some of the files/variables to simplify.
SliderAdapter:
public class SliderAdapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
private ArrayList<String> text;
public SliderAdapter(Context context, ArrayList<String> text) {
this.context = context;
this.text = text;
}
public String[] txtH = {
"test1",
"test2",
"test3"
};
#Override
public int getCount() {
return txtH.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == (ConstraintLayout) object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.slide_layout_wr, container, false);
TextView txt1 = view.findViewById(R.id.txt11);
TextView txt2 = view.findViewById(R.id.txt22);
txt1.setText(txtH[position]);
txt2.setText(text.get(position));
container.addView(view);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((ConstraintLayout) object);
}
}
Dialog itself:
public class DialogWeeklyReport extends AppCompatDialogFragment {
...
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),
R.style.Dialog);
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog, null);
preferences = getActivity().getSharedPreferences("label", 0);
Random random = new Random();
text.add("test1");
text.add("test2");
text.add("test3");
viewPager = view.findViewById(R.id.viewPager);
dotLayout = view.findViewById(R.id.dotLayout);
next = view.findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (next.getText().toString().equals("Proceed")) {
dismiss();
} else {
viewPager.setCurrentItem(currentPage + 1);
}
}
});
back = view.findViewById(R.id.back);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewPager.setCurrentItem(currentPage--);
}
});
builder.setView(view)
.setCancelable(true);
addDotsIndicator(0);
viewPager.setOnPageChangeListener(viewListener);
adapter = new SliderAdapter(getActivity(), text);
return builder.create();
}
private void addDotsIndicator(int position) {
dots = new TextView[3];
dotLayout.removeAllViews();
for (int i = 0; i<dots.length; i++) {
dots[i] = new TextView(getActivity());
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(Color.parseColor("#404040"));
dotLayout.addView(dots[i]);
}
if(dots.length > 0) {
dots[position].setTextColor(Color.BLACK);
}
if (currentPage == 0) {
back.setEnabled(false);
next.setEnabled(true);
back.setText("");
next.setText("Next");
}
}
ViewPager.OnPageChangeListener viewListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
addDotsIndicator(position);
currentPage = position;
if (currentPage == 0) {
back.setEnabled(false);
next.setEnabled(true);
back.setText("");
next.setText("Next");
} else if (currentPage == 1) {
back.setEnabled(true);
next.setEnabled(true);
back.setText("Back");
next.setText("Next");
} else if (currentPage == 2) {
back.setEnabled(true);
next.setEnabled(false);
back.setText("Back");
next.setText("Proceed");
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
}
Dialog XML:
<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="wrap_content"
android:background="#drawable/dialog_bg"
app:cardCornerRadius="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="#+id/dotLayout"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_centerHorizontal="true"
android:layout_margin="15dp"
android:layout_below="#+id/viewPager"
android:orientation="horizontal" />
<Button
android:id="#+id/back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_below="#+id/viewPager"
android:background="#android:color/transparent"
android:elevation="0dp"
android:text="Back"
android:textColor="#android:color/black" />
<Button
android:id="#+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_below="#+id/viewPager"
android:layout_margin="5dp"
android:background="#android:color/transparent"
android:elevation="0dp"
android:text="Next"
android:textColor="#android:color/black" />
</RelativeLayout>
ViewPager's slide layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
android:background="#android:color/white">
<TextView
android:id="#+id/txt11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEST"
android:textColor="#android:color/black"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.24000001" />
<TextView
android:id="#+id/txt22"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Test"
android:textColor="#android:color/black"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/txt11"
app:layout_constraintStart_toStartOf="#+id/txt11"
app:layout_constraintTop_toBottomOf="#+id/txt11"
app:layout_constraintVertical_bias="0.26" />
</androidx.constraintlayout.widget.ConstraintLayout>
The problem is that you didn't set the ViewPager adapter
public class DialogWeeklyReport extends AppCompatDialogFragment {
...
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
...
viewPager = view.findViewById(R.id.viewPager);
...
adapter = new SliderAdapter(getActivity(), text);
viewPager.setAdapter(adapter); // <<<<<< change here
return builder.create();
}
...
Here is my test
Related
I want to make an internal grid view(room) added by clicking the button on the external recycler view(floor). but Null pointer extension occurs in onBindViewHolder. please help me
public class FloorAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements OnFloorItemClickListener {
OnFloorItemClickListener listener;
static public ArrayList<FloorData> floors;
private Context context;
private LayoutInflater layoutInflater;
private OnItemClickListener mListener = null;
public FloorAdapter(ArrayList<FloorData> floors, Context context) {
this.floors = floors;
this.context = context;
this.layoutInflater = LayoutInflater.from(context);
}
public interface OnItemClickListener{
void onItemClick(View v, int pos);
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.mListener = listener ;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.signle_floor, parent, false);
return new GridViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((GridViewHolder)holder).recyclerView.setAdapter(new RoomAdapter(context, floors.get(position).rooms));
((GridViewHolder)holder).recyclerView.setLayoutManager(new GridLayoutManager(context, 2));
((GridViewHolder)holder).recyclerView.setHasFixedSize(true);
((GridViewHolder)holder).tvFloorNum.setText(String.valueOf(floors.get(position).floorNum));
}
#Override
public int getItemCount() {
return floors.size();
}
#Override public void onItemClick(RecyclerView.ViewHolder holder, View view, int position) {
if(listener != null){
listener.onItemClick(holder,view,position);
}
}
#Override
public int getItemViewType(int position) {
return floors.get(position).id;
}
public class GridViewHolder extends RecyclerView.ViewHolder {
RecyclerView recyclerView;
TextView tvFloorNum;
Button btnPlusRoom;
public GridViewHolder(View itemView) {
super(itemView);
recyclerView = itemView.findViewById(R.id.rvRooms);
tvFloorNum = itemView.findViewById(R.id.tvRoomNumber);
btnPlusRoom = (Button)itemView.findViewById(R.id.btnPlusRoom);
btnPlusRoom.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v)
{
int pos = getAdapterPosition();
if (pos != RecyclerView.NO_POSITION)
{
if(mListener != null){
mListener.onItemClick(v, pos);
}
}
}
});
}
}
}
public class RoomAdapter extends RecyclerView.Adapter<RoomAdapter.CustomViewHolder> {
private Context context;
private ArrayList<RoomData> rooms;
private LayoutInflater inflater;
public RoomAdapter(Context context, ArrayList<RoomData> rooms) {
this.context = context;
this.rooms = rooms;
this.inflater = LayoutInflater.from(context);
}
#Override
public CustomViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
view = inflater.inflate(R.layout.single_room, parent, false);
return new CustomViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull CustomViewHolder holder, int position) {
RoomData room = rooms.get(position);
holder.tvRoomNum.setText(String.valueOf(room.roomNum));
}
#Override
public int getItemCount() {
return rooms.size();
}
public static class CustomViewHolder extends RecyclerView.ViewHolder {
public TextView tvRoomNum;
public CustomViewHolder(View itemView) {
super(itemView);
tvRoomNum = (TextView) itemView.findViewById(R.id.tvRoomNumber);
}
}
}
public class RoomActivity extends AppCompatActivity {
private RecyclerView rvFloor;
private FloorAdapter floorAdapter;
public ArrayList<FloorData> globalfloors;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_room);
globalfloors = prepareData();
rvFloor = findViewById(R.id.rvFloors);
floorAdapter = new FloorAdapter(globalfloors, RoomActivity.this);
LinearLayoutManager manager = new LinearLayoutManager(RoomActivity.this);
rvFloor.setLayoutManager(manager);
rvFloor.setAdapter(floorAdapter);
floorAdapter.setOnItemClickListener(new FloorAdapter.OnItemClickListener() {
#Override
public void onItemClick(View v, int position) {
FloorData floor = globalfloors.get(position);
RoomData newRoom = new RoomData();
floor.finalRoomNum++;
newRoom.roomNum = floor.finalRoomNum;
floor.rooms.add(newRoom);
rvFloor.setAdapter(floorAdapter);
}
});
}
private ArrayList<FloorData> prepareData() {
ArrayList<FloorData> floors = new ArrayList<FloorData>();
//첫번째 subject 추가
FloorData floor1 = new FloorData();
floor1.floorNum = 1;
RoomData room101 = new RoomData();
room101.roomNum = 101;
RoomData room102 = new RoomData();
room102.roomNum = 102;
RoomData room103 = new RoomData();
room103.roomNum = 103;
floor1.finalRoomNum = 103;
floor1.rooms.add(room101);
floor1.rooms.add(room102);
floor1.rooms.add(room103);
floors.add(floor1);
FloorData floor2 = new FloorData();
floor2.floorNum = 2;
floor2.finalRoomNum = 200;
floors.add(floor2);
return floors;
}
}
activity_room
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".tools.RewardActivity"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolBar_room"
android:layout_width="match_parent"
android:layout_gravity="center"
android:layout_height="60dp"
android:background="#color/colorPrimaryDark"
app:title="호실 등록"
android:theme="#style/ToolbarTheme" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rvFloors"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
single_floor
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:orientation="vertical"
android:background="#FFFFFF"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="15dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/tvFloorNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:textSize="30dp"
android:textColor="#000000" />
<Button
android:id="#+id/btnPlusRoom"
android:layout_width="40dp"
android:layout_height="40dp"
android:text="+"
android:textSize="30dp"
android:layout_marginTop="10dp"
android:background="#color/colorPrimaryDark"/>
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:columnCount="5"
android:id="#+id/rvRooms"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</LinearLayout>
single_room
<LinearLayout 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="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="2dp">
<TextView
android:id="#+id/tvRoomNumber"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
android:ellipsize="end"
android:singleLine="true"
android:background="#color/colorAccent"
android:gravity="center"
android:textSize="30dp"
/>
</LinearLayout>
</LinearLayout>
error message describes "java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.eos.parcelnoticemanager.tools.FloorAdapter.onBindViewHolder"
The GridViewHolder inside your FloorAdapter is pointing to the wrong XML Id tag for the TextView that's why it's throwing NullPointerException
Change this in your GridViewHolder
tvFloorNum = itemView.findViewById(R.id.tvRoomNumber);
to this
tvFloorNum = itemView.findViewById(R.id.tvFloorNumber);
Then it should work
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
I'm developing an English-Japanese learning app, where it has a stack of cards where users can swipe through, and on each current card, the user can touch the card to flip to the other side of a card, which show the meaning of the word.
For the swipe function, I'm using a library SwipeFlingAdapterView, which support setOnItemClick. Now I need to do the flipping part. I read the tutorial here, which requires 2 fragments to do the flip:
https://developer.android.com/training/animation/cardflip.html
The structure Im setting below:
stack_of_cards_fragment.xml
<FrameLayout 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"
......
>
<com.lorentzos.flingswipe.SwipeFlingAdapterView
android:id="#+id/swipeFlingAdapterViewFront"
android:layout_width="match_parent"
android:layout_height="match_parent"
</com.lorentzos.flingswipe.SwipeFlingAdapterView>
</FrameLayout>
StackOfCardsFragment.java
public class StackOfCardsFragment extends Fragment {
ArrayList<TestModel> cardsList;
Context context;
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.stack_of_cards_fragment,container,false);
final CardsAdapter arrayCardsAdapter;
cardsList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
//dump data
TestModel model = new TestModel();
model.isFlipped = false;
cardsList.add(model);
}
SwipeFlingAdapterView flingContainer = ButterKnife.findById(view,R.id.swipeFlingAdapterViewFront);
ButterKnife.bind(this, view);
arrayCardsAdapter = new CardsAdapter(context, cardsList);
flingContainer.setAdapter(arrayCardsAdapter);
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
#Override
public void removeFirstObjectInAdapter() {
Log.d("LIST", "removed object!");
if(!cardsList.isEmpty())
{arrayCardsAdapter.remove(0);}
}
#Override
public void onLeftCardExit(Object dataObject) {
Log.e("Swipe Direction","Left");
}
#Override
public void onRightCardExit(Object dataObject) {
Log.e("Swipe Direction","Right");
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
if(!cardsList.isEmpty()) {
arrayCardsAdapter.notifyDataSetChanged();
Log.d("LIST", "notified");
}else Log.e("Check Empty","Its empty");
}
#Override
public void onScroll(float scrollProgressPercent) {
Log.e("onScroll", "scrollProgressPercent");
}
});
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
//This is where I want to change the Front Card Fragment to Back Card Fragment.
}
});
return view;
}
}
and below is the part where I'm struggling to do.
flash_card_layout.xml
<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="wrap_content"
android:background="#android:color/holo_blue_dark">
<LinearLayout
android:id="#+id/child_fragment_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
CardsAdapter.java
public class CardsAdapter extends BaseAdapter {
Context context;
ArrayList<TestModel> cardsList;
ViewFlipper viewFlipper;
public CardsAdapter(Context context, ArrayList cardsList ) {
this.context = context;
this.cardsList = cardsList;
}
#Override
public int getCount() {
return cardsList.size();
}
#Override
public Object getItem(final int i) {
return cardsList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int i, View view, final ViewGroup viewGroup) {
if (view == null) {
LayoutInflater vi = (LayoutInflater) viewGroup.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.flash_card_layout, viewGroup, false);
//This is where I want to set the Front Card Fragment
Fragment frontCardFragment = new EachFrontCardFragment();
FragmentTransaction transaction = ((VocabularyGameActivity) context).getSupportFragmentManager().beginTransaction();
transaction.addToBackStack(null);
transaction.add(R.id.child_fragment_container, frontCardFragment);
transaction.commit();
}
return view;
}
public void remove(int i) {
cardsList.remove(i);
notifyDataSetChanged();
}
}
each_card_front_fragment.xml and one for the each_card_back_fragment.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/cardviewfront">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingTop="20dp"
android:paddingLeft="20dp"
android:paddingRight="20dp">
<TextView android:id="#+id/txtWord_cardfront"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="English"
android:textStyle="bold"
android:textSize="50sp"
android:textColor="#android:color/black"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:layout_marginBottom="50dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"/>
</LinearLayout>
</android.support.v7.widget.CardView>
</FrameLayout>
I already created 2 fragments for each_card_front_fragment and each_card_back_fragment.
What am I missing here? All the code above is only showing me the cardAdapter in the StackOfCardsFragment(which is only a background), but the each_card_front_fragment doesn't show up.
I already try set up a BroadcastReceiver from (CardsAdapter)BaseAdapter to send to the VocabulartyActivity to set the each_card_front_fragment there but the same outcome.
is the any other way to set the Fragment in the BaseAdapter?
I'm with a problem to add more than 1 line(item) in my RecyclerView, the item overwrites the previous one when I tap the button, but if I create a List<> with data in hardcoded on onCreate, It works adding more than 1 line in the RecyclerView. Follow the code:
ListChecklistAdapter
public class ListChecklistAdapter extends RecyclerView.Adapter<ListChecklistAdapter.ListChecklistViewHolder> {
private List<Checklist> mChecklist;
private Context mCtx;
public ListChecklistAdapter(Context ctx, List<Checklist> checklists) {
mCtx = ctx;
mChecklist = checklists;
}
#Override
public ListChecklistViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mCtx).inflate(R.layout.item_checklist, parent, false);
return new ListChecklistViewHolder(view);
}
#Override
public void onBindViewHolder(ListChecklistViewHolder holder, int position) {
holder.cbItem.setText(mChecklist.get(position).getDescricao());
holder.cbItem.setChecked(mChecklist.get(position).isCheckado());
}
#Override
public int getItemCount() {
return mChecklist.size();
}
public class ListChecklistViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.item_checkbox)
CheckBox cbItem;
public ListChecklistViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
public void refreshData(List<Checklist> item) {
this.mChecklist.clear();
this.mChecklist.addAll(item);
notifyDataSetChanged();
}
}
item_checklist
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<CheckBox
android:id="#+id/item_checkbox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:paddingLeft="6dp"
android:text=" "
tools:text="Exemplo de item de lista" />
</RelativeLayout>
MainActivity
public class MainActivity extends AppCompatActivity {
#BindView(R.id.rcv_lista)
RecyclerView rvLista;
int valor;
private List<Checklist> lista;
private ListChecklistAdapter listChecklistAdapter;
#BindView(R.id.btn_add_item)
Button btnAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
private int cont() {
return valor++;
}
public void novoItem(View view) {
lista = new ArrayList<>();
lista.add(new Checklist("Item " + (cont() + 1), true));
loadRecycler(lista);
}
private void loadRecycler(List<Checklist> lista) {
if (listChecklistAdapter == null) {
Log.i("LOG", "IF");
listChecklistAdapter = new ListChecklistAdapter(this, lista);
rvLista.setAdapter(listChecklistAdapter);
rvLista.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
rvLista.addItemDecoration(new DividerItemDecoration(this, 1));
return;
} else {
Log.i("LOG", "ELSE");
listChecklistAdapter.refreshData(lista);
listChecklistAdapter.onAttachedToRecyclerView(rvLista);
}
}
}
activity_main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context="teste.com.br.recyclercomcheckbox.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/rcv_lista"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/btn_add_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginTop="5dp"
android:background="#android:color/transparent"
android:onClick="novoItem"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:text="+ novo item"
android:textColor="#009688" />
</LinearLayout>
Just remove this line this.mChecklist.clear(); from your refreshData() method.
public void refreshData(List<Checklist> item) {
this.mChecklist.addAll(item);
notifyDataSetChanged();
}
#Nilesh Rathod solved the problem! I just deleted this.mChecklist.clear(); from the ListCheckAdapter.java > refreshData()
Thanks for everyone to help too!
I am developing an bus time table android app. I have three fragments.
Inside first fragment I have two radio buttons i.e. From Malegaon & To Malegaon. (Malegaon is name of place).
If I select From Malegaon radio button then I am setting text to sourceEditText as Malegaon. and If I select To Malegaon radio button then I am setting text to destinationEditText as Malegaon.
This condition is working fine, when I visit fragment first time, but if I revisit fragment then From Malegaon radio Button is already selected, sourceEditText is blank and destinationEditText has text as Malegaon.
Here is my snapshot and code for first fragment.
after selecting to Malegaon radio button.
I am just changing visibility of layout. (source edittext,destination edittext,search button is one layout)
OldStandFragment.java
public class OldStandFragment extends Fragment {
public static OldStandFragment fragment ;
private static final String ARG_POSITIONS = "position";
private int positions;
private View myFragmentViewOld;
private LinearLayout fromOldMalegoanView, toOldMalegoanView;
Button selectRouteButton;
public static final String required_dest = "Please Enter Destination";
public static final String required_source = "Please Enter Source";
String language = "";
DbHelper helper;
private String sourceId = "", destinationId = "";
private ArrayList<Route> myArrayList;
private RouteAdapter routeAdapter;
private ListView routeListView;
private EditText sourceEditTextFromMalegoanOld;
private EditText destinationEditTextFromMalegoanOld;
private ImageButton searchFromMalegoanButtonOld;
private EditText sourceEditTextToMalegoanOld;
private EditText destinationEditTextToMalegoanOld;
private ImageButton searchToMalegoanButtonOld;
private RadioButton fromOldMalegoanRadioButton, toOldMalegoanRadioButton;
public OldStandFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
positions = getArguments().getInt(ARG_POSITIONS);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myFragmentViewOld = inflater.inflate(R.layout.fragment_old_stand, container, false);
selectRouteButton = (Button) myFragmentViewOld.findViewById(R.id.selectRouteButton);
fromOldMalegoanRadioButton = (RadioButton) myFragmentViewOld.findViewById(R.id.fromOldMalegoanRadioButton);
toOldMalegoanRadioButton = (RadioButton) myFragmentViewOld.findViewById(R.id.toOldMalegoanRadioButton);
fromOldMalegoanView = (LinearLayout) myFragmentViewOld.findViewById(R.id.fromOldMalegoanView);
toOldMalegoanView = (LinearLayout) myFragmentViewOld.findViewById(R.id.toOldMalegoanView);
sourceEditTextFromMalegoanOld = (EditText) fromOldMalegoanView.findViewById(R.id.sourceEditText);
destinationEditTextFromMalegoanOld = (EditText) fromOldMalegoanView.findViewById(R.id.destinationEditText);
searchFromMalegoanButtonOld = (ImageButton) fromOldMalegoanView.findViewById(R.id.searchResultButton);
sourceEditTextToMalegoanOld = (EditText) toOldMalegoanView.findViewById(R.id.sourceEditText);
destinationEditTextToMalegoanOld = (EditText) toOldMalegoanView.findViewById(R.id.destinationEditText);
searchToMalegoanButtonOld = (ImageButton) toOldMalegoanView.findViewById(R.id.searchResultButton);
SharedPreferences prefs = getContext().getSharedPreferences("MyPrefsFile", Context.MODE_PRIVATE);
int a = prefs.getInt("LangValue", 0);
if (a == 0) {
language = "English";
} else {
language = "मराठी";
}
helper = new DbHelper(getContext());
fromOldMalegoanRadioButton.setChecked(true);
toOldMalegoanRadioButton.setChecked(false);
fromOldMalegoanView.setVisibility(View.VISIBLE);
toOldMalegoanView.setVisibility(View.GONE);
String stopValue = helper.getStopName("1", language);
sourceEditTextFromMalegoanOld.setText(stopValue);
fromOldMalegoanRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (fromOldMalegoanRadioButton.isChecked()) {
toOldMalegoanRadioButton.setChecked(false);
fromOldMalegoanView.setVisibility(View.VISIBLE);
toOldMalegoanView.setVisibility(View.GONE);
helper = new DbHelper(getContext());
String stopValue1 = helper.getStopName("1", language);
sourceEditTextFromMalegoanOld.setText(stopValue1);
destinationEditTextFromMalegoanOld.setText("");
}
}
});
toOldMalegoanRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (toOldMalegoanRadioButton.isChecked()) {
fromOldMalegoanRadioButton.setChecked(false);
fromOldMalegoanView.setVisibility(View.GONE);
toOldMalegoanView.setVisibility(View.VISIBLE);
helper = new DbHelper(getContext());
String stopValue2 = helper.getStopName("1", language);
destinationEditTextToMalegoanOld.setText(stopValue2);
sourceEditTextToMalegoanOld.setText("");
}
}
});
searchFromMalegoanButtonOld.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//search result code.
}
});
searchToMalegoanButtonOld.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//search result code.
}
});
return myFragmentViewOld;
}
public static OldStandFragment newInstance(int position) {
if(fragment == null) {
fragment = new OldStandFragment();
}
Bundle bundle = new Bundle();
bundle.putInt(ARG_POSITIONS, position);
fragment.setArguments(bundle);
return fragment;
}
}
fragment_old_stand.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#000000"
android:scrollbars="vertical"
tools:context="com.ashishkudale.malegoanagar.Fragments.OldStandFragment">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<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">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Direction or Route"
android:gravity="center"
android:textColor="#FFFFFF"
android:id="#+id/Note"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_margin="15dp" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioGroup
android:id="#+id/rg_ContainerOld"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginTop="15dp">
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="From Malegaon"
android:id="#+id/fromOldMalegoanRadioButton"
android:layout_marginLeft="5dp"
android:checked="false" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<include
android:id="#+id/fromOldMalegoanView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/source_destination"
android:layout_margin="5dp" />
</LinearLayout>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="To Malegaon"
android:id="#+id/toOldMalegoanRadioButton"
android:layout_marginLeft="5dp" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<include
android:id="#+id/toOldMalegoanView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/source_destination"
android:layout_margin="5dp" />
</LinearLayout>
</RadioGroup>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Select Route "
android:id="#+id/selectRouteButton"
android:background="#drawable/button_effect"
android:layout_gravity="center_horizontal"
android:layout_margin="5dp" />
</LinearLayout>
</ScrollView>
this is Adapter to call fragment.
MyPagerAdapter
public class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = {"Old Stand","New Stand", "Fare"};
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
android.support.v4.app.Fragment fragment = null;
if(position ==0) {
fragment = OldStandFragment.newInstance(position);
}else if(position ==1 ){
fragment = NewStandFragment.newInstance(position);
} else if (position == 2) {
fragment = MapFragment.newInstance(position);
}
return fragment;
}
}
after revisiting OldStandFragment it look like this.
I checked with adding logs everywhere possible. And I found that after revisiting OldStandFragment, toOldMalegoanRadioButton.setOnClickListner() method is getting called.
Now I want to refresh fragment when I re-visit or any other way to solve this issue.
You have to use SharedPreferences to save state of checkbox, try this code
public class StackOne extends AppCompatActivity {
SharedPreferences prefs;
private RadioButton rButton1, rButton2;
private RadioGroup rg_ContainerOld;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stack_one);
prefs = PreferenceManager.getDefaultSharedPreferences(StackOne.this);
rButton1 = (RadioButton) findViewById(R.id.fromOldMalegoanRadioButton);
rButton2 = (RadioButton) findViewById(R.id.toOldMalegoanRadioButton);
rg_ContainerOld = (RadioGroup) findViewById(R.id.rg_ContainerOld);
GetSelectedRadioButton();
int k = prefs.getInt("rb1", 0);
if (k == 1) {
rButton1.setChecked(true);
sourceEditTextFromMalegoanOld.setText("");
} else if (k == 2) {
rButton2.setChecked(true);
sourceEditTextToMalegoanOld.setText("");
}
}
private void GetSelectedRadioButton() {
rg_ContainerOld.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (group.getCheckedRadioButtonId()) {
case R.id.fromOldMalegoanRadioButton:
prefs.edit().putInt("rb1", 1).commit();
break;
case R.id.toOldMalegoanRadioButton:
prefs.edit().putInt("rb1", 2).commit();
break;
}
}
});
}
}
In your code you are dynamically setting checked state of radiobutton
fromOldMalegoanRadioButton.setChecked(true);
toOldMalegoanRadioButton.setChecked(false);
thats why your radiobutton's oncheckedchanged method will get call. And thats why code in it.