fragments not displaying in framelayout - java

Intro:
To put things into perspective, I am attempting to use fragments to create a Sudoku game.
The Sudoku board consists of 9 sub-grids, each containing 9 cells, so 9 cells in one grid, and 9 of these grids form the Sudoku board, arranged in a 3x3 fashion.
Method:
Home screen containing some information, of which a GridLayout contains 9 Framelayouts where each Sudoku Fragment will be placed into
The 9 Sudoku Fragments will make up the Sudoku board.
sudoku_cell extends a LinearLayout with an onClickListener, since extending a TextView, I was unable to inflate the sudoku_cell layout (Is it possible to do so?)
In my main activity, I have a GridLayout containing 9 FrameLayouts. These layouts have column and row locations set to form a 3x3 matrix, this is where each of the fragments will be added into.
These FrameLayouts are named on a 0-based index: frame00, frame01, frame02, frame10, etc
Documentation says:
As mentioned here on developer.android.com, I am required to have an:
Inflator method for the fragment, i.e. onCreateView() which inflates the fragment
A Layout container of sorts to root/place the fragment in, in the main activity (in my case)
A FragmentManager and FragmentTransactionManager to handle the fragments, adding and commiting them.
Problem:
TL;DR: Simply, my fragments are not showing.
After calling the commit(), I expect to see a 3x3 board of sudoku_grid fragments, each containing 9 sudoku_cells. However, this does not get shown
I have searched SO, reread the documentation, and searched more but cannot understand why it is not showing.
I have tried:
When inflating my fragment, I inflate a sudoku_cell layout instead, this does infact show a 9 cell grid.
However each cell should be a grid containing 9 cells, this leads me to believe that there may be an issue on the Sudoku_Grid - Sudoku_Cell side, possibly the sudoku_cell layout is not being inflated correctly or being rooted correctly.
Usually an LayoutInflator, and ViewGroup is passed allowing one to inflate a layout, but in the case of the sudoku_cell, I cannot find such a method to override, is this the cause?
The code:
sudoku_cell.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">
<TextView
android:id="#+id/cellText"
android:layout_width="35dp"
android:layout_margin="1px"
android:textSize="18dp"
android:layout_height="35dp"
android:textAlignment="center"
android:textColor="#color/clBlack">
</TextView>
</LinearLayout>
SudokuCell.java
public class SudokuCell extends LinearLayout{
private LinearLayout layout;
private TextView textView;
private Context mContext;
private Point location;
private int index;
public SudokuCell(Context context) {
super(context);
}
public SudokuCell(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layout = (LinearLayout) inflater.inflate(R.layout.sudoku_cell, this, true);
textView = layout.findViewById(R.id.cellText);
setText("");
}
public void setStaticText(String s){
if (textView != null) {
textView.setText(s);
textView.setTypeface(textView.getTypeface(), Typeface.BOLD);
}
}
public void setText(String s){
if (textView != null)
textView.setText(s);
}
public Point getLocation() {
return location;
}
public void setLocation(Point location) {
this.location = location;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
9 of these sudoku_cell's get added to a sudoku_grid as shown below in the onCreateView() and populateGrid() methods:
sudoku_grid.xml
<?xml version="1.0" encoding="utf-8"?>
<GridLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="2px"
android:id="#+id/grid_layout"
android:columnCount="3"
android:rowCount="3">
</GridLayout>
SudokuGrid.java
public class SudokuGrid extends Fragment{
private GridLayout gridLayout;
private List<GridFragmentListener> listeners = new ArrayList<>();
private Context mActitityContext;
private boolean FRAGMENT_LOCATION_CENTRE;
private float SCREEN_DP;
private int GRID_MARGINS_DP = 1;
private int colorOdd, colorEven;
private List<Integer> presetGrid;
private View previousView;
private Drawable previousViewDrawable;
public void addGridListener(GridFragmentListener gridFragmentListener) {
listeners.add(gridFragmentListener);
}
public void removeGridListener(GridFragmentListener gridFragmentListener) {
listeners.remove(gridFragmentListener);
}
protected void notifyValueChanged(View value) {
for (GridFragmentListener listener : listeners) listener.onValueChange(value);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mActitityContext = getActivity();
View v = inflater.inflate(R.layout.sudoku_grid, container, false);
//set grid view
gridLayout = v.findViewById(R.id.grid_layout);
populateGrid();
return v;
}
private void populateGrid() {
for (int i = 0; i < 9; i++) {
SudokuCell sudokuCell = new SudokuCell(mActitityContext);
sudokuCell.setBackgroundColor(((i % 2) == 0) ? R.color.clOdd : R.color.clEven);
System.out.printf("Sudoku Cell ID [ index = " + String.valueOf(i) + " ] - getId() = " + sudokuCell.getId());
sudokuCell.setLocation(getPoint(i));
sudokuCell.setIndex(i);
sudokuCell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
notifyValueChanged(view);
}
});
sudokuCell.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean b) {
SudokuCell cell = (SudokuCell) view;
if (b)
view.setBackgroundColor(ContextCompat.getColor(mActitityContext, R.color.clSelected));
else
view.setBackgroundColor(ContextCompat.getColor(mActitityContext, (cell.getIndex() % 2 == 0) ? R.color.clOdd : R.color.clEven));
}
});
sudokuCell.setStaticText(String.valueOf(i));
gridLayout.addView(sudokuCell, i);
}
}
private Point getPoint(int i) {
int y = 0;
while (i > 2){
y++;
i -= 3;
}
return new Point(i, y);
}
#Override
public void onStart() {
super.onStart();
try {
addGridListener((GridFragmentListener) getActivity());
} catch (ClassCastException e) {
throw new ClassCastException(
getActivity().getClass().toString()
+ " does not implement the DetailsFragment.DetailsFragmentListener interface.");
}
}
#Override
public void onStop() {
super.onStop();
removeGridListener((GridFragmentListener) getActivity());
}
}
In my main activity, I handle the creation of 9 sudoku_grid fragments which are placed into each respective FrameLayout, to form a 3x3 matrix of Sudoku_Grids, which will form the Sudoku board
activity_main_sudoku.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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"
tools:context="wrap302.nmu.task1.MainActivitySudoku"
android:background="#color/clDarkGrey">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:id="#+id/linearLayout2">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:text="#string/app_title"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:textColor="#color/clWhite"
android:textAppearance="#style/TextAppearance.AppCompat.Display1"
android:textAlignment="center"
android:textStyle="bold"
android:fontFamily="sans-serif"/>
<TextView
android:text="#string/lblScore"
android:textColor="#color/clWhite"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:id="#+id/lblScore"
android:textAppearance="#style/TextAppearance.AppCompat.Button" android:textAlignment="center"
android:layout_marginBottom="5dp"/>
</LinearLayout>
<GridLayout
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnCount="3"
android:rowCount="3"
android:id="#+id/main_sudokugrid_container">
<FrameLayout
android:layout_column="0"
android:layout_row="0"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame00"/>
<FrameLayout
android:layout_column="1"
android:layout_row="0"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame01"/>
<FrameLayout
android:layout_column="2"
android:layout_row="0"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame02"/>
<FrameLayout
android:layout_column="0"
android:layout_row="1"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame10"/>
<FrameLayout
android:layout_column="1"
android:layout_row="1"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame11"/>
<FrameLayout
android:layout_column="2"
android:layout_row="1"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame12"/>
<FrameLayout
android:layout_column="0"
android:layout_row="2"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame20"/>
<FrameLayout
android:layout_column="1"
android:layout_row="2"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame21"/>
<FrameLayout
android:layout_column="2"
android:layout_row="2"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame22"/>
</GridLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="center" android:id="#+id/linearLayout">
<GridLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:paddingTop="0dp">
<Button
android:layout_row="0"
android:layout_column="0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn1"
android:text="1"/>
<Button
android:layout_row="0"
android:layout_column="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn2"
android:text="2"/>
<Button
android:layout_row="0"
android:layout_column="2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn3"
android:text="3"/>
<Button
android:layout_row="1"
android:layout_column="0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn4"
android:text="4"/>
<Button
android:layout_row="1"
android:layout_column="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn5"
android:text="5"/>
<Button
android:layout_row="1"
android:layout_column="2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn6"
android:text="6"/>
<Button
android:layout_row="2"
android:layout_column="0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn7"
android:text="7"/>
<Button
android:layout_row="2"
android:layout_column="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn8"
android:text="8"/>
<Button
android:layout_row="2"
android:layout_column="2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn9"
android:text="9"/>
<Button
android:layout_row="0"
android:layout_column="3"
android:layout_rowSpan="3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_vertical"
android:id="#+id/btnClear"
android:text="Clear"/>
</GridLayout>
</LinearLayout>
</RelativeLayout>
MainActivitySudoku.java
public class MainActivitySudoku extends AppCompatActivity implements GridFragmentListener {
private FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_sudoku);
createSudokuGrid();
}
private void createSudokuGrid() {
fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransactionManager = fragmentManager.beginTransaction();
fragmentTransactionManager.add(R.id.frame00, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame01, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame02, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame10, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame11, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame12, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame20, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame21, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame22, new SudokuGrid());
fragmentTransactionManager.commit();
}
#Override
protected void onStart() {
super.onStart();
Toast.makeText(this, "Activity Started & Viewable", Toast.LENGTH_SHORT).show();
}
// GridFragmentListener
#Override
public void onValueChange(View view) {
//todo something here with received view
}
}

Well, the solution proved simpler than expected.
In short, the solution was to move the SudokuCell constructor code from the
SudokuCell(Context context, AttributeSet attrs)
to the
SudokuCell(Context context)
since that was the constructor I was calling.
A few other changes can be made for improvement, this solves the fragments not being displayed.
Quite a simple error

Ok - I have given you a sample of how to add your fragments so they will display. If you go through this and emulate the process this will assist you. I've used basic examples in the layout so we can have ids to use in the classes.
You'll also need to manage the app lifecycle and the back press button on how you want to manage your stack with your fragments and maintaining any data.
Activity
public class MyActivity extends Activity {
Fragment fragment;
FrameLayout frameLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_myactivity);
View view = this.findViewById(android.R.id.content);
frameLayout = (FrameLayout) findViewById(R.id.frag);
fragment = new MyFragment();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.frag, fragment);
fragmentTransaction.commit();
}
}
Layout for Activity
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
.../...>
.../...
<FrameLayout
android:id="#+id/frag"
// sort out your layout here with the frameLayouts
android:layout_below="#+id/your_id"
/>
.../...
</RelativeLayout>
Fragment
public class MyFragmentextends Fragment {
FragmentManager fragmentManager;
Fragment fragment;
public static MyFragmentnewInstance(String item {
fragment =
new MyFragment();
// pass data from activity
Bundle args = new Bundle();
args.putString(ITEM, item);
fragment.setArguments(args);
return fragment;
}
public DeliveryDisplayFromDispenserFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
item = getArguments().getString(ITEM);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view =
inflater.inflate(R.layout.myfragment, container, false);
}
}
Layout for Fragment
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
.../...>
// fragment layout
</RelativeLayout>

Related

Create the Recycler view with fixed item count in horizontal scroll

Please help Me,
I am trying to create a specific type of recycler view which can have always 3 items in all kind of mobile phone. Whether that mobile is having 4 inch display or 6.5 inch display.
Please tell me if that is possible or not.
my code of xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:id="#+id/recomended"
android:layout_margin="6dp"
android:background="#drawable/graycurverdbtn"
android:layout_height="170dp">
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="85dp"
android:scaleType="fitCenter"
android:src="#drawable/mountain">
</ImageView>
<LinearLayout
android:layout_width="match_parent"
android:layout_margin="10dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="15dp"
android:gravity="center"
>
<TextView
android:id="#+id/pinkbtn"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#drawable/pinkcurvedbtn"
android:gravity="center"
android:padding="3dp"
android:text="Recomended"
android:textColor="#color/white"
android:textSize="9dp">
</TextView>
</LinearLayout>
<LinearLayout
android:layout_below="#id/image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="8dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="normal"
android:layout_margin="6dp"
android:layout_gravity="center"
android:textSize="10sp"
android:textColor="#color/black"
android:text="Pest control">
</TextView>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/grey"></View>
<TextView
android:layout_margin="8dp"
android:id="#+id/shopname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="10dp"
android:textStyle="bold"
android:textColor="#color/black"
android:text="K02BgbhdAf">
</TextView>
<TextView
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/graylocation"
android:text="Airport Road"
android:id="#+id/address"
android:textSize="18sp"
android:textStyle="normal">
</TextView>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
This is my Adapter code
public class OurrecomendedAdapter extends RecyclerView.Adapter<OurrecomendedAdapter.MyViewHolder> {
private List<HomeResponse.Recommend> ourrecomendedlist = new ArrayList<>();
private Context context;
public static int recomendedid=0;
public OurrecomendedAdapter(List<HomeResponse.Recommend> list, Context context) {
this.ourrecomendedlist = list;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recomemdedservices_item, parent, false);
// itemView.setLayoutParams(new ViewGroup.LayoutParams((int) (parent.getWidth() * 0.3),ViewGroup.LayoutParams.MATCH_PARENT));
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, #SuppressLint("RecyclerView") int position) {
holder.title.setText(ourrecomendedlist.get(position).getCategory().getSlug());
holder.shopname.setText(ourrecomendedlist.get(position).getCategory().getName());
Picasso.get().load(ourrecomendedlist.get(position).getImage()).into(holder.image, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError(Exception e) {
}
});
holder.recomended.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(ourrecomendedlist.get(position).getCategory().getName().toString().equalsIgnoreCase("salon for women") || ourrecomendedlist.get(position).getCategory().getName().toString().equalsIgnoreCase("salon for men")){
AppCompatActivity activity = (AppCompatActivity) context;
WomensalonlistFragment subc = new WomensalonlistFragment();
Bundle args = new Bundle();
args.putString("id", ourrecomendedlist.get(position).getProductcategoryId().toString());
args.putString("title", ourrecomendedlist.get(position).getName());
subc.setArguments(args);
activity.getSupportFragmentManager().beginTransaction().addToBackStack(null).
replace(R.id.nav_host_fragment, subc).commit();
}
else
{
typeListid= ourrecomendedlist.get(position).getId().toString();
Intent intent= new Intent(context, ProductdetailsActivity.class);
intent.putExtra("productId",typeListid);
context.startActivity(intent);
HomeFragment.vendormainid=ourrecomendedlist.get(position).getId().toString();
}
}
});
}
#Override
public int getItemCount() {
return this.ourrecomendedlist.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView name,title,shopname,address,pinkbtn;
Button addtocart;
ImageView image;
RelativeLayout recomended;
MyViewHolder(View itemView) {
super(itemView);
addtocart=itemView.findViewById(R.id.addtocart);
image=itemView.findViewById(R.id.image);
title=itemView.findViewById(R.id.title);
shopname=itemView.findViewById(R.id.shopname);
address=itemView.findViewById(R.id.address);
recomended=itemView.findViewById(R.id.recomended);
name=itemView.findViewById(R.id.name);
pinkbtn=itemView.findViewById(R.id.pinkbtn);
}
}
}
in this i need to display our output as 3 items in each aspect-ratio mobile.
but I'm unable to achieve that. If I'm opening in big screen mobile then it's showing 3.5 items and in small device some times it's showing 2.75 items.
Kindly help me in that how to achieve that exact output.

Can the RecyclerView scroll with the rest of the fragment layouts?

I have set up a RecyclerView adapter with ViewPager in an activity namely TvShowEpisodeDetails , it works well but there is one issue, the Layout of RecyclerView is fixed while scrolling up and down in the Fragment(TvShowEpisodeDetailsFragment). But I want it to scroll with them.
The RecyclerView and ViewPager are both set inside viewpager_with_toolbar_overlay.xml Layout , and both has been settup in The Activity.
TvShowEpisodeDetailsFragment is the fragment class which belongs to activity class TvShowEpisodeDetails , the fragment creates as many episodes as a TV Show season can offer.
And off course this issue will be gone if I set RecyclerView adapter inside fragment, but I will get non-fixable highlighting and scrolling issues , that is why I set it inside the activity because it does not give those issues.
I need to make it work somehow inside the activity.
My goal is that RecyclerView and ViewPager has to be in the same layout XML file and they both must either be in the activity or fragment class
Is it possible to make the RecyclerView scroll with rest of the fragment layouts?
or
Is it possible to do it programmatically?
Here is the activity
public class TvShowEpisodeDetails extends MizActivity{
#Override
protected int getLayoutResource() {
return R.layout.viewpager_with_toolbar_overlay;
}
#Override
public void onCreate(Bundle savedInstanceState) {
mBus = MizuuApplication.getBus();
super.onCreate(savedInstanceState);
// Set theme
setTheme(R.style.Mizuu_Theme_NoBackground);
// setting episodeslist
final ArrayList<PlanetModel> episodeslist = new ArrayList<>();
for(TvShowEpisode e : mEpisodes){
episodeslist.add(new PlanetModel(e.mEpisode));
}
// setting RecyclerView
mEpisodesList = (RecyclerView) findViewById(R.id.episodesLIST);
// Setting LinearLayoutManager
LinearLayoutManager layoutManager
= new LinearLayoutManager(this.getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
//mEpisodesList.setLayoutManager(new LinearLayoutManager(mContext));
mEpisodesList.setLayoutManager(layoutManager);
// Setting RecyclerView Adapter
PlanetAdapter.OnItemClickListener indicatorCallback = new PlanetAdapter.OnItemClickListener() {
#Override
public void onItemClick(String item) {
SharedPreferences getPref = getContext().getSharedPreferences("PlanetAdapter", Context.MODE_PRIVATE);
int pos = getPref.getInt("newPosition", 0);
mViewPager.setCurrentItem(pos,false);
}
};
final PlanetAdapter planetAdapter = new PlanetAdapter(episodeslist,indicatorCallback);
mEpisodesList.setAdapter(planetAdapter);
// Setting ViewPager
mViewPager = (ViewPager) findViewById(R.id.awesomepager);
mViewPager.setAdapter(new TvShowEpisodeDetailsAdapter(getSupportFragmentManager()));
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
planetAdapter.setSelectedIndex(position);
planetAdapter.notifyDataSetChanged();
mEpisodesList.smoothScrollToPosition(position);
//mEpisodesList.scrollToPosition(position);
for (int i=0; i<episodeslist.size(); i++)
{
episodeslist.get(i).setPlanetSelected(false);
}
episodeslist.get(position).setPlanetSelected(true);
ViewUtils.updateToolbarBackground(TvShowEpisodeDetails.this, mToolbar, 0, mEpisodes.get(position).getTitle(), Color.TRANSPARENT);
}
});
if (savedInstanceState != null) {
mViewPager.setCurrentItem(savedInstanceState.getInt("tab", 0));
} else {
for (int i = 0; i < mEpisodes.size(); i++) {
if (mEpisodes.get(i).getSeason().equals(MizLib.addIndexZero(mSeason)) && mEpisodes.get(i).getEpisode().equals(MizLib.addIndexZero(mEpisode))) {
mViewPager.setCurrentItem(i);
break;
}
}
}
}
}
viewpager_with_toolbar_overlay
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.ViewPager
android:id="#+id/awesomepager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="#+id/progressbar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#068006"
android:layout_marginTop="450dp"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/episodesLIST"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:scrollbars="horizontal" />
</LinearLayout>
<include layout="#layout/toolbar_layout" />
</FrameLayout>
Here is the XML layout of the fragment which is inflated in onCreateView of the fragment class
episode_details.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/abc_input_method_navigation_guard">
<com.miz.views.ObservableScrollView
android:id="#+id/observableScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/episodePhoto"
android:layout_width="match_parent"
android:layout_height="#dimen/backdrop_portrait_height"
android:scaleType="centerCrop"
android:src="#drawable/bg" />
<com.melnykov.fab.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/episodePhoto"
android:layout_alignParentEnd="false"
android:layout_alignParentRight="true"
android:layout_marginTop="#dimen/content_details_fab_negative_margin"
android:layout_marginRight="#dimen/content_details_baseline_margin"
android:src="#drawable/ic_play_arrow_white_36dp"
app:fab_colorNormal="#666"
app:fab_type="mini" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/fab"
android:layout_marginLeft="#dimen/content_details_baseline_margin"
android:layout_marginTop="#dimen/content_details_title_margin_top"
android:layout_marginRight="#dimen/content_details_baseline_margin"
android:layout_toLeftOf="#+id/fab"
android:orientation="vertical">
<TextView
android:id="#+id/movieTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="3"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_title" />
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/content_details_very_small_margin"
android:layout_marginBottom="#dimen/content_details_baseline_margin"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_subheader"
android:textStyle="bold|italic" />
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:id="#+id/details_area"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#666"
android:baselineAligned="false"
android:elevation="1dp"
android:minHeight="#dimen/content_details_large_margin"
android:orientation="horizontal"
android:paddingLeft="#dimen/content_details_baseline_margin"
android:paddingTop="#dimen/content_details_small_margin"
android:paddingRight="#dimen/content_details_baseline_margin"
android:paddingBottom="#dimen/content_details_small_margin">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:gravity="center_horizontal"
android:lines="1"
android:maxLines="1"
android:text="#string/detailsAirDate"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="#dimen/content_details_area_subheader" />
<TextView
android:id="#+id/textReleaseDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_area_header"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/textView61"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:gravity="center_horizontal"
android:lines="1"
android:maxLines="1"
android:text="#string/detailsRating"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="#dimen/content_details_area_subheader" />
<TextView
android:id="#+id/textView12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_area_header"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="#dimen/content_details_baseline_margin">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/content_details_baseline_margin"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/director"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:drawableLeft="#drawable/ic_movie_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:focusable="false"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f0f0f0"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/writer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:drawableLeft="#drawable/ic_edit_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:focusable="false"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f0f0f0"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/guest_stars"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:drawableLeft="#drawable/ic_people_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:focusable="false"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f0f0f0"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_folder_open_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_body_text" />
</LinearLayout>
</LinearLayout>
</com.miz.views.ObservableScrollView>
<FrameLayout
android:id="#+id/progress_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg"
android:visibility="gone">
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</FrameLayout>
</FrameLayout>
Update
Fragment
#SuppressLint("InflateParams") public class TvShowEpisodeDetailsFragment extends Fragment {
public TvShowEpisodeDetailsFragment() {}
public static TvShowEpisodeDetailsFragment newInstance(String showId, int season, int episode) {
TvShowEpisodeDetailsFragment pageFragment = new TvShowEpisodeDetailsFragment();
Bundle bundle = new Bundle();
bundle.putString("showId", showId);
bundle.putInt("season", season);
bundle.putInt("episode", episode);
pageFragment.setArguments(bundle);
return pageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
mContext = getActivity();
mBus = MizuuApplication.getBus();
mShowFileLocation = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean(SHOW_FILE_LOCATION, true);
mPicasso = MizuuApplication.getPicassoDetailsView(getActivity());
mMediumItalic = TypefaceUtils.getRobotoMediumItalic(mContext);
mMedium = TypefaceUtils.getRobotoMedium(mContext);
mCondensedRegular = TypefaceUtils.getRobotoCondensedRegular(mContext);
mDatabaseHelper = MizuuApplication.getTvEpisodeDbAdapter();
LocalBroadcastManager.getInstance(mContext).registerReceiver(mBroadcastReceiver,
new IntentFilter(LocalBroadcastUtils.UPDATE_TV_SHOW_EPISODE_DETAILS_OVERVIEW));
loadEpisode();
}
#Override
public void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mBroadcastReceiver);
}
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
loadEpisode();
loadData();
}
};
private void loadEpisode() {
if (!getArguments().getString("showId").isEmpty() && getArguments().getInt("season") >= 0 && getArguments().getInt("episode") >= 0) {
Cursor cursor = mDatabaseHelper.getEpisode(getArguments().getString("showId"), getArguments().getInt("season"), getArguments().getInt("episode"));
if (cursor.moveToFirst()) {
mEpisode = new TvShowEpisode(getActivity(),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SHOW_ID)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_TITLE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_PLOT)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_AIRDATE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_DIRECTOR)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_WRITER)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_GUESTSTARS)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_RATING)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_HAS_WATCHED)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_FAVOURITE))
);
mEpisode.setFilepaths(MizuuApplication.getTvShowEpisodeMappingsDbAdapter().getFilepathsForEpisode(
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SHOW_ID)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE))
));
}
cursor.close();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.episode_details, container, false);
}
#Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mBackdrop = (ImageView) view.findViewById(R.id.imageBackground);
mEpisodePhoto = (ImageView) view.findViewById(R.id.episodePhoto);
mDetailsArea = view.findViewById(R.id.details_area);
mTitle = (TextView) view.findViewById(R.id.movieTitle);
mSeasonEpisodeNumber = (TextView) view.findViewById(R.id.textView7);
mDescription = (TextView) view.findViewById(R.id.textView2);
mFileSource = (TextView) view.findViewById(R.id.textView3);
mAirDate = (TextView) view.findViewById(R.id.textReleaseDate);
mRating = (TextView) view.findViewById(R.id.textView12);
mDirector = (TextView) view.findViewById(R.id.director);
mWriter = (TextView) view.findViewById(R.id.writer);
mGuestStars = (TextView) view.findViewById(R.id.guest_stars);
mScrollView = (ObservableScrollView) view.findViewById(R.id.observableScrollView);
mFab = (FloatingActionButton) view.findViewById(R.id.fab);
mFab.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ViewUtils.animateFabJump(v, new SimpleAnimatorListener() {
#Override
public void onAnimationEnd(Animator animation) {
play();
}
});
}
});
...
}
...
}
I have set up a RecyclerView adapter with ViewPager in an activity namely TvShowEpisodeDetails , it works well but there is one issue, the Layout of RecyclerView is fixed while scrolling up and down in the Fragment(TvShowEpisodeDetailsFragment). But I want it to scroll with them.
It's hard to use the RecyclerView outside of the ViewPager page fragment; because you can't synchronize and link the touch/motion events when you scroll the page up/down (or when you swipe to next/previous page) between both the page fragment and a standalone (i.e. activity) RecyclerView. Even that won't be smooth.
So, the RecyclerView should be a part of the ViewPager page.
And off course this issue will be gone if I set RecyclerView adapter inside fragment, but I will get unfixable highlighting and scrolling issues
So, now the issue of adding the RecyclerView in the ViewPager fragment is the highlighting issue of the RecyclerView item when you click on any item or when you swipe the ViewPager to right/left page.
But, the main issue is that there is a RecyclerView instance per page, i.e. if you have 5 pages, then you have 5 RecyclerViews.
So, it's a cumbersome to track highlighting only within the RecyclerView adapter class. And hence manipulating that with OnClickListeners solely will have issues of linking these RecyclerView and adapter instances together to update their highlighting item.
So, a simpler approach is to pass a parameter to the RecyclerView adapter with the selected item (which is definitely equals to the current ViewPager page position).
And then do a check in the onBindViewHolder() if the position equals to the passed-in value, then highlight the item; otherwise keep items with the original color.
So, wrapping this up into actions:
Change the adapter constructor to accept a highlighted_position parameter
public PlanetAdapter(ArrayList<PlanetModel> episodeslist,
int highlightedPosition, OnItemClickListener listener)
Whenever you create the ViewPager fragment using newInstance() pass-in the current position of the page fragment:
So, in the TvShowEpisodeDetails activity:
for (int i = 0; i < mEpisodes.size(); i++)
fragments.add(TvShowEpisodeDetailsFragment
.newInstance(mShowId,
Integer.parseInt(mEpisodes.get(i).getSeason()),
Integer.parseInt(mEpisodes.get(i).getEpisode()),
i)); // The position
And in the TvShowEpisodeDetailsFragment fragment, register this into a field in the fragment argument:
public static TvShowEpisodeDetailsFragment newInstance(String showId, int season, int episode, int position) { // adding position
TvShowEpisodeDetailsFragment pageFragment = new TvShowEpisodeDetailsFragment();
Bundle bundle = new Bundle();
// trimmed code.
bundle.putInt("position", position); // <<<< into the bundle
pageFragment.setArguments(bundle);
return pageFragment;
}
And set that in the adapter creation:
int currentPosition = getArguments().getInt("position");
planetAdapter = new PlanetAdapter(episodeslist, currentPosition, new PlanetAdapter.OnItemClickListener() {
#Override
public void onItemClick(final int pos) {
mCallback.sendText(pos);
}
});
And reflect that in the adapter to highlight the item:
public class PlanetAdapter extends RecyclerView.Adapter<PlanetAdapter.PlanetViewHolder> {
private final int highlightedPos;
public PlanetAdapter(ArrayList<PlanetModel> episodeslist, int highlightedPosition, OnItemClickListener listener) {
this.episodeslist = episodeslist;
this.listener = listener;
this.highlightedPos = highlightedPosition; // <<< set the position
}
#Override
public void onBindViewHolder(PlanetAdapter.PlanetViewHolder vh, final int position) {
TextView tv = (TextView) vh.itemView;
PlanetModel planetModel = episodeslist.get(position);
tv.setText(planetModel.getPlanetName());
tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.bg, 0, 0, 0);
if (highlightedPos == position) { //<<<<< Highlight the item
vh.itemView.setBackgroundColor(getContext().getResources().getColor(R.color.colorPrimaryLight));
Log.d("LOG_TAG", "onClick: Highlight item: " + highlightedPos);
} else {
vh.itemView.setBackgroundColor(getContext().getResources().getColor(R.color.colorPrimaryDark));
Log.d("LOG_TAG", "onClick: No highlight: " + highlightedPos);
}
}
}

issue in working with SwipeDeck2 lib

I've used SwipeDeck2, I set every thing and it is working, but I have one issue that is I can not set OnClickListener correctly on one of the views in card I have layout as
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/root_cv"
style="#style/CardViewStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="24dp"
android:elevation="5dp"
app:cardCornerRadius="7dp"
android:layout_gravity="top">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<org.team.asl.me_c.ui.DynamicHeightImageView
android:id="#+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="88dp"
android:scaleType="fitCenter"
app:heightRatio="1.0"
android:background="#color/grey_white_1000"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="vertical"
android:gravity="center_vertical"
android:padding="16dp"
android:background="#color/indigo_A200"
android:layout_gravity="bottom">
<TextView android:layout_marginTop="-15dp"
android:id="#+id/display_name_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#android:color/white"
android:fontFamily="sans-serif"
android:textStyle="bold"
android:textSize="22sp"/>
<TextView
android:id="#+id/username_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#android:color/white"
android:fontFamily="sans-serif"
android:textSize="16sp"/>
</LinearLayout>
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clipChildren="true">
<ImageButton
android:id="#+id/btnLike"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_gravity="top|right"
android:background="#android:color/transparent"
android:src="#drawable/ic_heart_outline_grey" />
<TextView
android:id="#+id/like_tv"
android:layout_width="120dp"
android:background="#drawable/shape_bg_green_rounded_rect"
android:layout_height="56dp"
android:gravity="center"
android:textSize="32sp"
android:text="LIKE"
android:textStyle="bold"
android:alpha="0"
android:layout_marginTop="32dp"
android:layout_marginBottom="32dp"
android:layout_marginLeft="24dp"
android:textColor="#android:color/holo_green_light"/>
<TextView
android:id="#+id/nope_tv"
android:layout_gravity="right"
android:layout_width="120dp"
android:background="#drawable/shape_bg_red_rounded_rect"
android:layout_height="56dp"
android:textSize="32sp"
android:gravity="center"
android:textStyle="bold"
android:text="NOPE"
android:alpha="0"
android:layout_marginTop="32dp"
android:layout_marginBottom="32dp"
android:layout_marginRight="24dp"
android:textColor="#android:color/holo_red_light"/>
</FrameLayout>
</FrameLayout>
</android.support.v7.widget.CardView>
and the adapter as
public class SwipeDeckAdapter extends BaseAdapter {
private List<String> data;
private Context context;
private int countLike = 0;
private ImageButton btnLike;
//private View.OnClickListener onClickListener;
public SwipeDeckAdapter(List<String> data, Context context) {
this.data = data;
this.context = context;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null){
LayoutInflater inflater = LayoutInflater.from(context);
// normally use a viewholder
v = inflater.inflate(R.layout.product_card, parent, false);
}
((TextView) v.findViewById(R.id.display_name_tv)).setText(data.get(position));
btnLike = (ImageButton) v.findViewById(R.id.btnLike);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String item = (String)getItem(position);
Log.e("MainActivity", item);
}
});
btnLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
countLike ++;
Log.e("LIKE_CONT", " is " + countLike);
btnLike.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_heart_red));
Toast.makeText(context, "Clicked at index ", Toast.LENGTH_SHORT).show();
}
});
return v;
}
}
I want to add click listener on btnLike and want to change the image resource in method
btnLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
countLike ++;
Log.e("LIKE_CONT", " is " + countLike);
btnLike.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_heart_red));
Toast.makeText(context, "Clicked at index ", Toast.LENGTH_SHORT).show();
}
});
but result is
means the image resource of btnLike is not changed in current card but as I shuffle cards and see on the other card the image resource of btnLike is changed any suggestions how to see that bit of code so that it can work properly...

Can't get Admob to show on multiple layouts?

I am trying to get Admob to display on my layout_one.xml and layout_two and can't get it to show. This app has a lot of swipe left and right and I want to display one ad over both layouts
Here are all my xml layouts:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/pager">
</android.support.v4.view.ViewPager>
layout_one.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/relative_one"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Copy"
android:id="#+id/Copy"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_alignParentEnd="false"
android:layout_alignParentStart="false"
android:textSize="30sp"
android:onClick="onClickCopy"/>
<EditText
android:layout_width="300dp"
android:layout_height="50dp"
android:id="#+id/stringCopy"
android:layout_above="#+id/Copy"
android:layout_centerHorizontal="true"
android:layout_marginBottom="70dp"
android:textSize="30sp"
android:inputType="text"
android:gravity="left|top"
android:background="#ffffff" />
<com.google.android.gms.ads.AdView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
ads:adSize="BANNER"
ads:adUnitId="#string/banner_ad_unit_id"/>
layout_two.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/relative_one"
android:background="#000000"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Paste"
android:id="#+id/Paste"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_alignParentEnd="false"
android:layout_alignParentStart="false"
android:textSize="30sp"
android:onClick="onClickPaste"/>
<EditText
android:layout_width="300dp"
android:layout_height="50dp"
android:id="#+id/stringCopy"
android:layout_marginBottom="71dp"
android:textSize="30sp"
android:inputType="text"
android:gravity="left|top"
android:background="#ffffff"
android:layout_above="#+id/Paste"
android:layout_centerHorizontal="true" />
<!-- SHOULD I PUT ANOTHER ADVIEW IN THIS XML -->
</RelativeLayout>
Here is all my java classes:
MainActivity.java
public class MainActivity extends FragmentActivity {
//View Pager
ViewPager viewpager;
//AdView
AdView adView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewpager = (ViewPager)findViewById(R.id.pager);
PagerAdapter pAdapter = new PagerAdapter(getSupportFragmentManager());
viewpager.setAdapter(pAdapter);
}
public void onClickCopy(View v)
{
//Copy Text From layout_one to Clipboard
}
public void onClickPaste(View v)
{
//Paste Text From Clipboard
}
}
PagerAdapter.java
public class PagerAdapter extends FragmentPagerAdapter {
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
switch (arg0) {
case 0:
return new FragmentOne();
case 1:
return new FragmentTwo();
default:
break;
}
return null;
}
#Override
public int getCount() {
return 2;
}
}
FragmentOne.java
public class FragmentOne extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.layout_one, container, false);
}
}
FragmentTwo.java
public class FragmentTwo extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.layout_two, container, false);
}
}
Where would I put this code so that when they swipe between layout_one and layout_two that the same ad will be displayed and not make a new ad request every time they change views?
//Display test Ads
adView = new AdView(this);
AdRequest request = new AdRequest.Builder()
.addTestDevice("DEVICE_ID").build();
adView.loadAd(request);
The standard pattern for doing this is to put your AdView either above or below your ViewPager and keep it static. That way you are not constantly requesting ads that you never get time to display.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
>
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="#+id/pager">
</android.support.v4.view.ViewPager>
<com.google.android.gms.ads.AdView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:adUnitId="yourAdUnitId"
android:id="#+id/adView">
</LinearLayout>
This way your Adview is outside your ViewPager and remains constant across all pages.
I use the following code to cache Admob in scroll Grid View:
public View getView(int position, View convertView, ViewGroup parent) {
if (position != adNum) {
...
} else {
if (mAdView == null) {
frameLayout = new FrameLayout(mContext);
mAdView = new AdView(mContext);
...
frameLayout.addView(mAdView);
} else {
frameLayout.removeView(mAdView);
frameLayout = new FrameLayout(mContext);
frameLayout.addView(mAdView);
}
return frameLayout;
}
}

Wrong values after rotation when more components with the same IDs are in one layout

I created a deletable EditText. Here is the layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" >
<EditText
android:id="#+id/cacEditText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:paddingRight="35dp" />
<Button
android:id="#+id/cacClearButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="5dp"
android:layout_marginRight="5dp"
android:background="#android:drawable/ic_input_delete"
android:visibility="invisible" />
</RelativeLayout>
The problem is that when I put more of these into one layout and rotate to landscape, they all suddenly have the same value. I suppose it is because the system restores the values by ID and each component consists of elements of the same IDs. How can I solve this problem?
More info:
deletable EditText (cz.kns.uome.component.CleanAndClearEditText) in a layout
<?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/cz.kns.uome"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<cz.kns.uome.component.CleanAndClearEditText
android:id="#+id/nameEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="#+id/contactPickerButton"
app:hint="#string/person_name"
app:type="textPersonName" />
<ImageButton
android:id="#+id/contactPickerButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:contentDescription="#string/select_contact"
android:src="#drawable/ic_action_dropdown" />
</RelativeLayout>
<cz.kns.uome.component.CleanAndClearEditText
android:id="#+id/emailEditText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
app:hint="#string/person_email_opt"
app:type="textEmailAddress" />
<cz.kns.uome.component.CleanAndClearEditText
android:id="#+id/descriptionEditText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
app:hint="#string/description_opt"
app:type="text" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/saveButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="5"
android:text="#string/save" />
<Button
android:id="#+id/cancelButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="#string/cancel" />
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
java class
public class CleanAndClearEditText extends RelativeLayout {
private final EditText editText;
private final Button clearButton;
public CleanAndClearEditText(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.clean_and_clear_edit_text, this);
TypedArray typedArray = getContext().obtainStyledAttributes(attrs,
R.styleable.ClearAndCleanEditText);
// ?????
// I have to somehow access that edittext here but static id does not work
editText = (EditText) findViewById(R.id.cacEditText);
editText.addTextChangedListener(textWatcher);
editText.setHint(typedArray.getString(R.styleable.ClearAndCleanEditText_hint));
String type = typedArray.getString(R.styleable.ClearAndCleanEditText_type);
if (type != null) {
editText.setInputType(InputTypes.get(type));
}
clearButton = (Button) findViewById(R.id.cacClearButton);
clearButton.setOnClickListener(clearButtonListener);
}
// rest ommited
}
I'm running on this issue, and I was able to "solve" this, by removing all views in the layout that contains the custom views, implement this:
public void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
// retain your data in the bundle then remove views
layout.removeAllViewsInLayout();
}
So you can get your data back from the bundle in the onCreate method.
See if this helps:
public class CleanAndClearEditText extends RelativeLayout {
private final EditText editText;
private final Button clearButton;
public CleanAndClearEditText(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.clean_and_clear_edit_text, this);
RelativeLayout rl = (RelativeLayout) getChildAt(0); // consider using a merge tag in R.layout.clean_and_clear_edit_text instead of the parent RelativeLayout
//clearButton = (Button) findViewById(R.id.cacClearButton);
clearButton = (Button) rl.getChildAt(1);
clearButton.setOnClickListener(null);
//editText = (EditText) findViewById(R.id.cacEditText);
editText = (EditText) rl.getChildAt(0);
}
#Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
ss.stateToSave = editText.getText().toString();
return ss;
}
#Override
protected void onRestoreInstanceState(Parcelable state) {
if (!(state instanceof SavedState)) {
super.onRestoreInstanceState(state);
return;
}
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
editText.setText(ss.stateToSave);
}
static class SavedState extends BaseSavedState {
String stateToSave;
SavedState(Parcelable superState) {
super(superState);
}
private SavedState(Parcel in) {
super(in);
stateToSave = in.readString();
}
#Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeString(stateToSave);
}
// required field that makes Parcelables from a Parcel
public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}
and the modified R.layout.clean_and_clear_edit_text file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" >
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:paddingRight="35dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:background="#android:drawable/ic_input_delete"
android:visibility="invisible" />
</RelativeLayout>
Edit:
The main part of the code is from the question I posted as a comment.
OK, I see you are inflating custom code and inserting it into a linearlayout. You should use a ListView and implement your ListAdapter. You can customize your ListItem to fit your needs.
That's the way I would do it.

Categories