The fragment only displays one cardview when I am trying to retrieve it from the news API.
Here is the code.
Main Activity
package com.manish.newapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create an instance of the tab layout from the view.
TabLayout tabLayout = findViewById(R.id.tab_layout);
// Set the text for each tab.
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label1));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label2));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label3));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label4));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label5));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label6));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label7));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label8));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label9));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label10));
// Set the tabs to scroll through the entire layout.
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
// Use PagerAdapter to manage page views in fragments.
// Each page is represented by its own fragment.
final ViewPager viewPager = findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
// Setting a listener for clicks.
viewPager.addOnPageChangeListener(new
TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new
TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
TabNews Fragment
package com.manish.newapp.Fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.manish.newapp.Adapter;
import com.manish.newapp.ApiClient;
import com.manish.newapp.Models.Articles;
import com.manish.newapp.Models.Headlines;
import com.manish.newapp.Models.Source;
import com.manish.newapp.R;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class TabNews1 extends Fragment {
View v;
RecyclerView recyclerView;
final String API_KEY = "5a1ad719eee94e7ba60d19b51f4ff159";
String sources = "bbc-news";
Adapter adapter;
List<Articles> articles = new ArrayList<>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// String country = getCountry();
// retrieveJson(country,API_KEY);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v= inflater.inflate(R.layout.fragment_tab_news1, container, false);
recyclerView = (RecyclerView)v.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
String country = getCountry();
retrieveJson(country,API_KEY);
// retrieveJson(sources,API_KEY);
// Inflate the layout for this fragment
return v;
}
public void retrieveJson(String country, String apiKey){
Call<Headlines> call = ApiClient.getInstance().getApi().getHeadlines(country,apiKey);
call.enqueue(new Callback<Headlines>() {
#Override
public void onResponse(Call<Headlines> call, Response<Headlines> response) {
if (response.isSuccessful() && response.body().getArticles() != null){
articles.clear();
articles = response.body().getArticles();
adapter = new Adapter(getContext(),articles);
recyclerView.setAdapter(adapter);
}
}
#Override
public void onFailure(Call<Headlines> call, Throwable t) {
Toast.makeText(getContext(), t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public String getCountry(){
Locale locale = Locale.getDefault();
String country = locale.getCountry();
return country.toLowerCase();
}
}
adapter Class
package com.manish.newapp;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.manish.newapp.Models.Articles;
import com.squareup.picasso.Picasso;
import java.util.List;
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
Context context;
List<Articles> articles;
public Adapter(Context context, List<Articles> articles) {
this.context = context;
this.articles = articles;
}
#NonNull
#Override
public Adapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.items_recycler,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull Adapter.ViewHolder holder, int position) {
Articles art = articles.get(position);
holder.txtTitle.setText(art.getTitle());
holder.txtDescription.setText(art.getDescription());
holder.txtDate.setText(art.getPublishedAt());
String imageUrl = art.getUrlToImage();
Picasso.with(context).load(imageUrl).into(holder.imageView);
}
#Override
public int getItemCount() {
return articles.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView txtTitle, txtDescription, txtDate, txtTime;
ImageView imageView;
CardView cardView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
txtTitle = (TextView)itemView.findViewById(R.id.title_text);
txtDescription = (TextView)itemView.findViewById(R.id.desc);
txtTime = (TextView)itemView.findViewById(R.id.time);
txtDate = (TextView)itemView.findViewById(R.id.date);
imageView = (ImageView)itemView.findViewById(R.id.image_news);
cardView = (CardView)itemView.findViewById(R.id.cardView);
}
}
}
Pager Adapter class
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import com.manish.newapp.Fragments.TabNews1;
import com.manish.newapp.Fragments.TabNews10;
import com.manish.newapp.Fragments.TabNews2;
import com.manish.newapp.Fragments.TabNews3;
import com.manish.newapp.Fragments.TabNews4;
import com.manish.newapp.Fragments.TabNews5;
import com.manish.newapp.Fragments.TabNews6;
import com.manish.newapp.Fragments.TabNews7;
import com.manish.newapp.Fragments.TabNews8;
import com.manish.newapp.Fragments.TabNews9;
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(#NonNull FragmentManager fm,int NumOfTabs) {
super(fm, NumOfTabs);
this.mNumOfTabs = NumOfTabs;
}
#NonNull
/**
* Return the Fragment associated with a specified position.
*
* #param position
*/
#Override
public Fragment getItem(int position) {
switch (position){
case 0 : return new TabNews1();
case 1 : return new TabNews2();
case 2 : return new TabNews3();
case 3 : return new TabNews4();
case 4 : return new TabNews5();
case 5 : return new TabNews6();
case 6 : return new TabNews7();
case 7 : return new TabNews8();
case 8 : return new TabNews9();
case 9 : return new TabNews10();
default: return null;
}
}
/**
* Return the number of views available.
*/
#Override
public int getCount() {
return mNumOfTabs;
}
}
Here are my layout files.
item_recycler.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/cardView"
android:layout_margin="16dp"
android:padding="10dp"
app:cardElevation="4dp"
app:cardCornerRadius="10dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp">
<ImageView
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="#+id/image_news"
android:src="#drawable/image"
android:scaleType="centerCrop"/>
<!-- <FrameLayout-->
<!-- android:layout_width="match_parent"-->
<!-- android:layout_height="wrap_content"-->
<!-- android:id="#+id/frame_layout"-->
<!-- android:layout_below="#+id/image_news"-->
<!-- android:padding="5dp">-->
<!-- <RelativeLayout-->
<!-- android:layout_width="match_parent"-->
<!-- android:layout_height="wrap_content">-->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TITLE"
android:textSize="20dp"
android:layout_below="#+id/image_news"
android:textStyle="bold"
android:id="#+id/title_text"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/desc"
android:text="DESCRIPTION"
android:layout_marginTop="10dp"
android:textSize="14dp"
android:layout_below="#+id/title_text"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/time"
android:layout_below="#+id/desc"
android:text="TIME"
android:layout_marginTop="5dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/date"
android:layout_below="#+id/time"
android:text="DATE"
android:layout_marginTop="5dp"/>
<!-- </RelativeLayout>-->
<!-- </FrameLayout>-->
</RelativeLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
fragment_tab_news1.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"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Fragments.TabNews1"
android:background="#color/colorBackground">
<!-- TODO: Update blank fragment layout -->
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!-- <TextView-->
<!-- android:layout_width="match_parent"-->
<!-- android:layout_height="wrap_content"-->
<!-- android:text="BBC NEWS"-->
<!-- android:textStyle="bold"-->
<!-- android:textSize="17sp"-->
<!-- android:layout_marginLeft="16dp"-->
<!-- android:layout_marginRight="16dp"-->
<!-- android:layout_marginTop="10dp"-->
<!-- android:fontFamily="sans-serif-light"/>-->
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
</androidx.core.widget.NestedScrollView>
</RelativeLayout>
Mainactivity.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=".MainActivity"
android:id="#+id/relative_main"
android:padding="16dp"
>
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<com.google.android.material.tabs.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/toolbar"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<androidx.viewpager.widget.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout"/>
</RelativeLayout>
Please help me with this, I am unable to find whats wrong here.
Related
I'm trying to show all the card views using recycler view in main activity. Although I did not set a huge margin between card views, my recycler view shows a huge space to print the next card view. please see my attached image, you'll understand what I'm trying to say. I've attached all the code here. Can you please advise how to solve this problem? Thank you.
<?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">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"
tools:listitem="#layout/note_card" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="50dp"
android:layout_marginRight="50dp"
android:layout_marginBottom="50dp"
android:clickable="true"
app:layout_constraintBottom_toBottomOf="#+id/recyclerView"
app:layout_constraintEnd_toEndOf="parent"
app:srcCompat="#drawable/add" />
</androidx.constraintlayout.widget.ConstraintLayout>
<?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"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.cardview.widget.CardView
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_margin="7dp"
app:cardBackgroundColor="#color/green"
app:cardCornerRadius="5dp"
app:cardElevation="5dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/textViewTitleCard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="TextView"
android:textSize="20sp" />
<TextView
android:id="#+id/textViewDescriptionCard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_marginTop="16dp"
android:text="TextView"
android:textSize="16sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
package com.destructivepaul.quicknote;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.NoteHolder>{
private List<MyNote> myNoteList = new ArrayList<>();
// private Context context;
public void setMyNoteList(List<MyNote> myNoteList) {
this.myNoteList = myNoteList;
notifyDataSetChanged();
Log.i("info","note updated on adapter. note list size: "+myNoteList.size());
}
//public void setContext(Context context) {
// this.context = context;
// notifyDataSetChanged();
// Log.i("info","context updated on adapter");
// }
#NonNull
#Override
public NoteHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.note_card
,parent,false);
return new NoteHolder(view);
}
#Override
public void onBindViewHolder(#NonNull NoteHolder holder, int position) {
MyNote myNote=myNoteList.get(position);
holder.textViewTitle.setText(myNote.getNote_title());
holder.textViewDescription.setText(myNote.getNote_description());
}
#Override
public int getItemCount() {
return myNoteList.size();
}
public class NoteHolder extends RecyclerView.ViewHolder{
private TextView textViewTitle, textViewDescription;
private CardView cardView;
public NoteHolder(#NonNull View itemView) {
super(itemView);
textViewTitle=itemView.findViewById(R.id.textViewTitleCard);
textViewDescription=itemView.findViewById(R.id.textViewDescriptionCard);
cardView=itemView.findViewById(R.id.cardView);
Log.i("info","card design found on adapter");
}
}
}
package com.destructivepaul.quicknote;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private FloatingActionButton fab;
private RecyclerView recyclerView;
private MyNoteViewModel myNoteViewModel;
private ActivityResultLauncher<Intent> activityResultLauncherForAddNote;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//resisterActivity
resisterActivityForAddNote();
fab=findViewById(R.id.fab);
recyclerView=findViewById(R.id.recyclerView);
NoteAdapter adapter=new NoteAdapter();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
Log.i("info","set the adapter");
myNoteViewModel = new ViewModelProvider.AndroidViewModelFactory(getApplication())
.create(MyNoteViewModel.class);
myNoteViewModel.getAllNotes().observe(MainActivity.this, new Observer<List<MyNote>>() {
#Override
public void onChanged(List<MyNote> myNotes) {
adapter.setMyNoteList(myNotes);
Log.i("info","adapter is called to update data");
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent =new Intent(MainActivity.this,CreateNoteActivity.class);
//resister activity launcher
activityResultLauncherForAddNote.launch(intent);
Log.i("info","called resister activity launcher on fab");
}
});
}
public void resisterActivityForAddNote(){
activityResultLauncherForAddNote=registerForActivityResult(new ActivityResultContracts.StartActivityForResult()
, new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
int resultCode=result.getResultCode();
Intent data = result.getData();
if (resultCode==RESULT_OK && data !=null) {
String title = data.getStringExtra("title");
String description = data.getStringExtra("description");
String colorName = data.getStringExtra("color");
MyNote myNote = new MyNote(title, description, colorName);
Log.i("info", "new note created on activity result");
myNoteViewModel.insert(myNote);
Log.i("info", "note saved to database");
}
}
});
}
}
I've solved my problem by myself. The problem was on card layout design(parent layout height should be wrap content instead of match parent).
I am unable to remove a present fragment in my second fragment while trying to replace it from the first fragment along with trying to open the second fragment from the first fragment on a click of a button.
Here is my code
FirstFragment.java
package com.example.testanderase;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.design.widget.TextInputEditText;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.List;
import java.util.Objects;
public class FirstFragment extends Fragment implements View.OnClickListener{
TextInputEditText inputEditText;
Button enterButton;
String getMessage;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.first_fragment,container,false);
inputEditText = view.findViewById(R.id.enter_edit_txt_input);
enterButton = view.findViewById(R.id.first_fragment_btn);
enterButton.setOnClickListener(this);
return view;
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onClick(View v) {
getMessage = inputEditText.getText().toString();
SecondFragment secondFragment = new SecondFragment();
Bundle b = new Bundle();
b.putString("data",getMessage);
secondFragment.setArguments(b);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.second_fragment_layout,secondFragment);
//transaction.add(R.id.second_fragment_layout,secondFragment);
transaction.commit();
***Below here I am trying to change the code
***In order to open the second fragment from the first fragment
/assert getFragmentManager() != null;
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.second_fragment_layout,secondFragment).commit();/
//fm.beginTransaction().replace(SecondFragment.newInstance());
}
}
first_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<LinearLayout
android:id="#+id/first_fragment_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginEnd="20dp">
<android.support.design.widget.TextInputEditText
android:id="#+id/enter_edit_txt_input"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="#string/input"
android:textAlignment="center"
android:gravity="center_horizontal" />
</android.support.design.widget.TextInputLayout>
<Button
android:id="#+id/first_fragment_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="#string/enter"
android:background="#color/black"
android:textColor="#color/white"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
/>
</LinearLayout>
</LinearLayout>
SecondFragment.java
package com.example.testanderase;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputEditText;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class SecondFragment extends Fragment implements View.OnClickListener{
TextView textView;
Button enterButton;
String firstFragmentValue;
Toast t;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.second_fragment,container,false);
textView = view.findViewById(R.id.second_fragment_txt_view);
enterButton = view.findViewById(R.id.second_fragment_btn);
enterButton.setOnClickListener(this);
//assert getArguments() != null;
//firstFragmentValue = getArguments().getString("data");
//textView.setText(firstFragmentValue);
Bundle bundle = getArguments();
if(bundle != null)
{
String name = bundle.getString("data");
textView.setText(name);
Toast.makeText(getContext(),"passed data "+name,Toast.LENGTH_SHORT).show();
}
//textView.setText(firstFragmentValue);
return view;
}
#Override
public void onClick(View v) {
//
ToastButton();
/*assert getFragmentManager() != null;
FirstFragment firstFragment = new FirstFragment();
FragmentManager fragmentTransaction = getFragmentManager();
fragmentTransaction.beginTransaction().replace(R.id.first_fragment_layout, firstFragment).commit();*/
}
public void ToastButton()
{
if(t!=null)
{
t.cancel();
}
else
{
Toast.makeText(getContext(),"Clicked",Toast.LENGTH_SHORT).show();
}
}
}
second_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<TextView
android:id="#+id/second_fragment_txt_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginEnd="20dp"
android:text="#string/change_text"
android:textAlignment="center"
android:gravity="center_horizontal"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
/>
<Button
android:id="#+id/second_fragment_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="#string/back_button_text"
android:background="#color/black"
android:textColor="#color/white"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
/>
</LinearLayout>
SectionPageAdapter.java
package com.example.testanderase;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;
public class SectionPageAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentListTitle = new ArrayList<>();
public void addFragment(Fragment fragment, String title)
{
fragmentList.add(fragment);
fragmentListTitle.add(title);
}
public SectionPageAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int i) {
return fragmentList.get(i);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return fragmentListTitle.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
}
MainActivity.java
package com.example.testanderase;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity{
private SectionPageAdapter mSectionPageAdapter;
private ViewPager mainViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionPageAdapter = new SectionPageAdapter(getSupportFragmentManager());
mainViewPager = findViewById(R.id.container);
setMainViewPager(mainViewPager);
TabLayout tabLayout = findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mainViewPager);
}
public void setMainViewPager(ViewPager viewPager)
{
SectionPageAdapter adapter = new SectionPageAdapter(getSupportFragmentManager());
adapter.addFragment(new FirstFragment(),"FIRST");
adapter.addFragment(new SecondFragment(),"SECOND");
viewPager.setAdapter(adapter);
}
}
activity_main.xml
<?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"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity"
android:id="#+id/main_layout"
android:layout_margin="20dp">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
where is R.id.second_fragment_layout
anyway change your second_fragment.xml to this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<LinearLayout
android:id="#+id/second_fragment_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<TextView
android:id="#+id/second_fragment_txt_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginEnd="20dp"
android:text="hello"
android:textAlignment="center"
android:gravity="center_horizontal"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
/>
<Button
android:id="#+id/second_fragment_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="back"
android:background="#000"
android:textColor="#fff"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
/>
</LinearLayout>
</LinearLayout>
and to open the second fragment from the first fragment on a click of a button
first make mainViewPager static
static ViewPager mainViewPager
put this on first fragment onclick
int page =1;
mainViewPager.setCurrentItem(page);
to back to first fragment
put this on second fragment onclick
int page =0;
mainViewPager.setCurrentItem(page);
ts working for me.!
I want to make Screen in android with multiple layouts. Fox example On the top of the screen there is the header with image slider (this part is done) below that there will be a list view and below that there will be grid view.
Activitymain.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"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.root.multipleview.MainActivity">
<!--Header image-->
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoStart="true"></android.support.v4.view.ViewPager>
<!--ListView Below header -->
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:height="10dp" />
</RelativeLayout>
CustomLayout.xml
<?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"
android:layout_alignParentTop="true"
android:background="#f1f3f7"
android:orientation="vertical">
<!--Header image with slider-->
<ImageView
android:id="#+id/headerimg"
android:layout_width="fill_parent"
android:layout_height="180dp"
android:scaleType="centerCrop"
android:layout_marginTop="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="4dp"
android:src="#mipmap/ic_launcher" />
<!--ListView Below Header-->
<RelativeLayout
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1"
android:layout_marginTop="20dp"
android:paddingLeft="2dp">
<ImageView
android:id="#+id/imageView"
android:layout_width="100dp"
android:layout_height="90dp"
android:layout_weight="0.05"
app:srcCompat="#mipmap/ic_launcher"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:gravity="center"/>
<TextView
android:id="#+id/textName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="40dp"
android:layout_marginStart="40dp"
android:layout_marginTop="11dp"
android:layout_toEndOf="#+id/imageView"
android:layout_toRightOf="#+id/imageView"
android:text="TextView" />
<TextView
android:id="#+id/textdesc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:layout_marginBottom="20dp"
android:layout_alignBottom="#+id/imageView"
android:layout_alignLeft="#+id/textName"
android:layout_alignStart="#+id/textName"/>
</RelativeLayout>
</LinearLayout>
ListView.java
package com.example.root.multipleview;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by root on 11/18/2017.
*/
public class ListView extends AppCompatActivity {
int[] Images = {R.drawable.salad,R.drawable.salami,R.drawable.flour,R.drawable.salt,
R.drawable.sandwich,R.drawable.sausage,R.drawable.seeds,R.drawable.cheese,R.drawable.shrimp,R.drawable.cupcake,R.drawable.cup,R.drawable.spices,R.drawable.cabbage
,R.drawable.spoon,R.drawable.apple,R.drawable.asparagus,R.drawable.cupcake,R.drawable.fish,R.drawable.corn,R.drawable.cupcake,R.drawable.spatula,R.drawable.olives
,R.drawable.garlic,R.drawable.taco,R.drawable.broccoli,R.drawable.cabbage};
String[] Names = {"a","B","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
String[] Description = {"VVV","DDD","ddd","dddsa","ddsdsds","zsxx","wwwwq","ddwqK","EQWK","FgggFFF","FFFkklF","FghhFFF","FFhhFF","FFhhFF",
"FFmmmFF","FgggFFF","FFFFbbb","FFFFfeee","gfffFFFF","FFFFfff","FFFgffF","FFFFfgffg","FFFfgfgfF","FFFgffF","FFFgfggdF","FFFFdssa"};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android.widget.ListView listView= (android.widget.ListView) findViewById(R.id.listView);
CustomAdapter customAdapter = new CustomAdapter();
listView.setAdapter(customAdapter);
}
public class CustomAdapter extends BaseAdapter {
#Override
public int getCount() {
return Images.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = getLayoutInflater().inflate(R.layout.custom_layout,null);
ImageView imageView = (ImageView)view.findViewById(R.id.imageView);
TextView textView_N = (TextView)view.findViewById(R.id.textName);
TextView textView_D = (TextView)view.findViewById(R.id.textdesc);
imageView.setImageResource(Images[i]);
textView_N.setText(Names[i]);
textView_D.setText(Description[i]);
return view;
}
}
}
MainActivity.java
package com.example.root.multipleview;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.viewPager);
ViewPageAdapter viewPageAdapter = new ViewPageAdapter( this);
viewPager.setAdapter(viewPageAdapter);
}
}
ViewPageAdapter
package com.example.root.multipleview;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
/**
* Created by root on 11/18/2017.
*/
public class ViewPageAdapter extends PagerAdapter{
private Context context;
private LayoutInflater layoutInflater;
private Integer[] images = {R.drawable.b,R.drawable.c,R.drawable.e,R.drawable.j,R.drawable.r,R.drawable.x,R.drawable.y};
public ViewPageAdapter(Context context){this.context = context;}
#Override
public int getCount() {
return images.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater =(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate((R.layout.custom_layout), null);
ImageView imageView = (ImageView) view.findViewById(R.id.headerimg);
imageView.setImageResource((images[position]));
ViewPager vp = (ViewPager) container;
vp.addView(view, 0);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
}
When I check this all layout separately it works but after adding in one layout it's not working. output screenshot is added
enter image description here
How to make multiple layout for one screen?
my approach for this goal is using Fragments
how?
i do make a single main_layout and set a FrameLayout in order to put fragments with different layouts.so i have a screen with different layouts.
this is my best answer for your question .
I want to add Recyclerview inside fragment then after that want to add fragment inside viewpager.So i follow tutorial on youtube.after compile..recyclerview is display but when i go to next tabs,exception appear.Hope you guys can help me solve this problem.
ERROR
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.recyclerviewpagerfragment, PID: 3705
java.lang.ClassCastException: android.support.v7.widget.LinearLayoutCompat cannot be cast to android.support.v7.widget.RecyclerView
at com.example.user.recyclerviewpagerfragment.Fragments.DocumentaryFragment.onCreateView(DocumentaryFragment.java:30)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2080)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1108)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1290)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:801)
at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1638)
at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:679)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1240)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1088)
at android.support.v4.view.ViewPager$3.run(ViewPager.java:275)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
at android.view.Choreographer.doCallbacks(Choreographer.java:670)
at android.view.Choreographer.doFrame(Choreographer.java:603)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I/Process: Sending signal. PID: 3705 SIG: 9
Application terminated.
MainActivity.java
package com.example.user.recyclerviewpagerfragment;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import com.example.user.recyclerviewpagerfragment.Fragments.CrimeFragment;
import com.example.user.recyclerviewpagerfragment.Fragments.DocumentaryFragment;
import com.example.user.recyclerviewpagerfragment.Fragments.DramaFragment;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//initialize view pager.
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager_id);
this.addPages(viewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_id);
//it gonna occupy the whole screen..
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(viewPager);
tabLayout.addOnTabSelectedListener(listener(viewPager));
}
// add all pages
private void addPages(ViewPager pager){
FragPagerAdapter adapter = new FragPagerAdapter(getSupportFragmentManager());
adapter.addPage(new CrimeFragment());
adapter.addPage(new DramaFragment());
adapter.addPage(new DocumentaryFragment());
//set adapter to pager
pager.setAdapter(adapter);
}
private TabLayout.OnTabSelectedListener listener(final ViewPager pager){
return new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
};
}
}
FragPagerAdapter.java
package com.example.user.recyclerviewpagerfragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
/**
* Created by User on 10/4/2016.
*/
public class FragPagerAdapter extends FragmentPagerAdapter{
//create arraylist..where its gonna hol fragment.
ArrayList<Fragment> pages = new ArrayList<>();
public FragPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return pages.get(position);
}
#Override
public int getCount() {
return pages.size();
}
// add a page
public void addPage(Fragment f){
pages.add(f);
}
//set title for tab
#Override
public CharSequence getPageTitle(int position) {
return pages.get(position).toString();
//return super.getPageTitle(position);
}
}
MyRecyclerAdapter.java
package com.example.user.recyclerviewpagerfragment.Recycler;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.example.user.recyclerviewpagerfragment.R;
import java.util.ArrayList;
/**
* Created by User on 10/4/2016.
*/
public class MyRecyclerAdapter extends RecyclerView.Adapter<MyViewHolder> {
Context context;
ArrayList<Movie> movies;
public MyRecyclerAdapter(Context context, ArrayList<Movie> movies) {
this.context = context;
this.movies = movies;
}
//initialize holder.
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.model,null);
MyViewHolder holder = new MyViewHolder(view);
return holder;
//return null;
}
//bind data to views
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.nameTxt.setText(movies.get(position).getImage());
holder.img.setImageResource(movies.get(position).getImage());
//listener
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Toast.makeText(context,movies.get(position).getName(),Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return movies.size();
}
}
MyViewHolder.java
package com.example.user.recyclerviewpagerfragment.Recycler;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.user.recyclerviewpagerfragment.R;
/**
* Created by User on 10/4/2016.
*/
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
ImageView img;
TextView nameTxt;
ItemClickListener itemClickListener;
public MyViewHolder(View itemView) {
super(itemView);
nameTxt = (TextView) itemView.findViewById(R.id.nameTxt);
img = (ImageView) itemView.findViewById(R.id.movieImage);
//above...if want to make click on nameTxt,can change itemView to nameTxt
itemView.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener){
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View view) {
this.itemClickListener.onItemClick(view,getLayoutPosition());
}
}
DocumentaryFragment.java
package com.example.user.recyclerviewpagerfragment.Fragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.user.recyclerviewpagerfragment.R;
import com.example.user.recyclerviewpagerfragment.Recycler.Movie;
import com.example.user.recyclerviewpagerfragment.Recycler.MyRecyclerAdapter;
import java.util.ArrayList;
/**
* Created by User on 10/4/2016.
*/
public class DocumentaryFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//call view
View view = inflater.inflate(R.layout.documentary_fragment,null);
//recyclerview
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.mRecyclerDocumentary);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
//set Adapter
recyclerView.setAdapter(new MyRecyclerAdapter(this.getActivity(),getDocumentaryMovies()));
return view;
//return super.onCreateView(inflater, container, savedInstanceState);
}
private ArrayList<Movie> getDocumentaryMovies() {
//collection of crime movies.
ArrayList<Movie> movies = new ArrayList<>();
//single movie
Movie movie = new Movie("Crime:tank5",R.drawable.e);
//add to collection..
movies.add(movie);
movie = new Movie("Crime:tank6",R.drawable.f);
movies.add(movie);
return movies;
/*
Movie movie = new Movie("tank1",R.drawable.a);
movies.add(movie);
Movie movie = new Movie("tank1",R.drawable.a);
movies.add(movie);
*/
}
//set title for the fragment
#Override
public String toString() {
return "Documentary";
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
tools:context="com.example.user.recyclerviewpagerfragment.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
<!-- add above for adding tablayout -->
<android.support.design.widget.TabLayout
android:id="#+id/tab_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_dialog_email" />
<!-- add above for adding viewpager -->
<android.support.v4.view.ViewPager
android:id="#+id/viewpager_id"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
Documentary_fragment.xml
<android.support.v7.widget.LinearLayoutCompat
android:id="#+id/mRecyclerDocumentary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></android.support.v7.widget.LinearLayoutCompat> </LinearLayout>
Model.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_margin="10dp"
card_view:cardCornerRadius="10dp"
card_view:cardElevation="10dp"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/movieImage"
android:padding="10dp"
android:src="#drawable/a"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Name"
android:id="#+id/nameTxt"
android:padding="10dp"
android:textColor="#color/colorAccent"
android:layout_below="#+id/movieImage"
android:layout_alignParentLeft="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="this tanks is awsome no need to jurge it."
android:id="#+id/descTxt"
android:layout_below="#+id/nameTxt"
android:layout_alignParentLeft="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="TV Show"
android:id="#+id/posTxt"
android:padding="10dp"
android:layout_below="#id/movieImage"
android:layout_alignParentRight="true"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/chk"
android:layout_alignParentRight="true"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
the error is
java.lang.ClassCastException: android.support.v7.widget.LinearLayoutCompat cannot be cast to android.support.v7.widget.RecyclerView
at com.example.user.recyclerviewpagerfragment.Fragments.DocumentaryFragment.onCreateView(DocumentaryFragment.java:30)
As it says the problem is in DocumentaryFragment, you are casting a LinearLayout to a ReciclerView, you should provide us that Fragment.
Hope it helps, I would like to comment but I do not have the requisites yet.
It uses retrofit 2.0 to fetch the data from the webservice and bind it to the card view. When I click on the card view having image and textviews, on click is not triggering, rather a strange behaviour is at the very corner edges of the card view onclick is triggering.
Item_row.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
card_view:cardCornerRadius="1dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp"
android:layout_margin="5dp"
android:clickable="true">
<ImageView
android:id="#+id/flowerImage"
android:layout_width="match_parent"
android:layout_height="200dp"
android:focusable="true"
android:clickable="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:visibility="visible"/>
<ImageButton
android:id="#+id/favIcon"
android:layout_width="32dp"
android:layout_height="32dp"
android:scaleType="fitXY"
android:layout_margin="5dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:descendantFocusability="blocksDescendants"
android:background="#drawable/ic_favorite_border"
android:focusable="true"
android:clickable="true"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/flowerImage"
android:orientation="vertical"
>
<TextView
android:id="#+id/flowerName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textColor="#color/colorPrimary"
android:textAppearance="?android:attr/textAppearanceMedium"
android:focusable="true"
android:clickable="true"
android:visibility="visible"/>
<TextView
android:id="#+id/flowerCategory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Small Text"
android:layout_alignBottom="#id/flowerName"
android:textAppearance="?android:attr/textAppearanceSmall"
android:focusable="true"
android:clickable="true"
android:visibility="visible"/>
<TextView
android:id="#+id/flowerPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#id/flowerCategory"
android:text="New Text"
android:focusable="true"
android:clickable="true"
android:visibility="visible"/>
<TextView
android:id="#+id/flowerInstruction"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:text="New Text"
android:focusable="true"
android:clickable="true"/>
</LinearLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
Content_main.xml
Layout file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_margin="8dp"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"/>
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
</LinearLayout>
Main Activity Layout file
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"
android:elevation="8dp"/>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
The code base is following MVC design pattern. Controller does the job of getting the web service data
MainActivity.java
package com.innovation.myapp.jwelleryonrent.View;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
import com.innovation.myapp.jwelleryonrent.R;
import com.innovation.myapp.jwelleryonrent.controller.jwelleryController;
import com.innovation.myapp.jwelleryonrent.model.adapter.CustomItemClickListner;
import com.innovation.myapp.jwelleryonrent.model.adapter.JwelleryAdapter;
import com.innovation.myapp.jwelleryonrent.model.pojo.JwelleryCollection;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements jwelleryController.JwelleryCallbackListener {
private Toolbar mToolbar;
private RecyclerView mRecyclerView;
private SwipeRefreshLayout mSwipeRefreshLayout;
private List<JwelleryCollection> mJwelleryList = new ArrayList<>();
private JwelleryAdapter mJwelleryAdapter;
private jwelleryController mController;
private boolean isInFavourites = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
configToolbar();
mController = new jwelleryController(MainActivity.this);
configViews();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.item_row, container, false);
ImageButton imgBtn = (ImageButton) findViewById(R.id.favIcon);
imgBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addItemToBag(v);
}
});
return rootView;
}
private void addItemToBag(View v)
{
isInFavourites = true;
ImageButton btnFaviourite = (ImageButton) findViewById(R.id.favIcon);
if(isInFavourites==true) {
btnFaviourite.setImageResource(R.drawable.ic_favorite_white_24dp);
}
else
btnFaviourite.setImageResource(R.drawable.ic_favorite_border);
Snackbar.make(v, "Item added to Favourites", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
private void configToolbar() {
mToolbar = (Toolbar) this.findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
}
private void initializeAdapter()
{
mJwelleryAdapter = new JwelleryAdapter(mJwelleryList, new CustomItemClickListner() {
#Override
public void onItemClick(View v, int position) {
Toast.makeText(MainActivity.this, "Clicked Item: "+position,Toast.LENGTH_LONG).show();
}
});
mRecyclerView.setAdapter(mJwelleryAdapter);
mSwipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorAccent),
getResources().getColor(R.color.colorPrimary),
getResources().getColor(R.color.colorPrimaryDark));
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mController.startFetching();
}
});
}
private void configViews() {
mRecyclerView = (RecyclerView) this.findViewById(R.id.list);
mSwipeRefreshLayout = (SwipeRefreshLayout) this.findViewById(R.id.swipe);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
mRecyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());
mController.startFetching();
initializeAdapter();
// mJwelleryAdapter= new JwelleryAdapter(mJwelleryList);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onFetchStart() {
}
#Override
public void onFetchProgress(JwelleryCollection jwellery) {
mJwelleryAdapter.addJwellery(jwellery);
}
#Override
public void onFetchProgress(List<JwelleryCollection> jwelleryList) {
}
#Override
public void onFetchComplete() {
mSwipeRefreshLayout.setRefreshing(false);
}
#Override
public void onFetchFailure() {
}
}
Recycler view uses the adapter view holder pattern to initialize the adapter
JwelleryAdapter class
package com.innovation.myapp.jwelleryonrent.model.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.innovation.myapp.jwelleryonrent.R;
import com.innovation.myapp.jwelleryonrent.View.MainActivity;
import com.innovation.myapp.jwelleryonrent.model.pojo.JwelleryCollection;
import com.innovation.myapp.jwelleryonrent.model.utilities.Constants;
import com.squareup.picasso.Picasso;
import java.util.List;
/**
*
*/
public class JwelleryAdapter extends RecyclerView.Adapter<JwelleryAdapter.Holder> {
private List<JwelleryCollection> mJwelleryCollection;
CustomItemClickListner itemListner;
Context mContext;
public JwelleryAdapter(List<JwelleryCollection> jwellery) {
mJwelleryCollection = jwellery;
}
public JwelleryAdapter( List<JwelleryCollection> jwellery,CustomItemClickListner listner) {
mJwelleryCollection = jwellery;
this.itemListner = listner;
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row,parent,false);
final Holder mViewHolder = new Holder(row);
row.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
itemListner.onItemClick(v,mViewHolder.getPosition());
}
});
return mViewHolder;
}
#Override
public void onBindViewHolder(JwelleryAdapter.Holder holder, int position) {
JwelleryCollection currentJwellery = mJwelleryCollection.get(position);
holder.mName.setText(currentJwellery.mName);
holder.mCategory.setText(currentJwellery.mCategory);
holder.mPrice.setText(Double.toString(currentJwellery.mPrice));
holder.mInstructions.setText(currentJwellery.mInstructions);
Picasso.with(holder.itemView.getContext()).load(Constants.PHOTO_URL + currentJwellery.mPhoto).into(holder.mImage);
}
public void addJwellery(JwelleryCollection jwellery) {
mJwelleryCollection.add(jwellery);
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return mJwelleryCollection.size();
}
public class Holder extends RecyclerView.ViewHolder implements View.OnClickListener {
Context contxt;
public TextView mName, mCategory, mPrice, mInstructions;
public ImageView mImage;
public Holder(View itemView) {
super(itemView);
mImage = (ImageView) itemView.findViewById(R.id.flowerImage);
mName = (TextView) itemView.findViewById(R.id.flowerName);
mCategory = (TextView) itemView.findViewById(R.id.flowerCategory);
mPrice = (TextView) itemView.findViewById(R.id.flowerPrice);
mInstructions = (TextView) itemView.findViewById(R.id.flowerInstruction);
}
public Holder(View itemView,int ViewType,Context c) {
// Creating ViewHolder Constructor with View and viewType As a parameter
super(itemView);
contxt = c;
itemView.setClickable(true);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Toast.makeText(contxt, "The Item Clicked is: " + getPosition(), Toast.LENGTH_SHORT).show();
}
}
}
CustomerItemClickListner Interface to handle row item on click
package com.innovation.myapp.jwelleryonrent.model.adapter;
import android.view.View;
/**
*
*/
public interface CustomItemClickListner {
public void onItemClick(View v,int position);
}
First create one variable of your interface in your adapter:
CustomItemClickListener mListener;
then like you have set in your OnClick() method:
if (mListener != null) {
mListener.onItemClick(v, getAdapterPosition());
}
and the last thing you need to modify in your adapter is creating new method which you will call later in your activity class for handling listener:
public void setOnItemClickListener(CustomItemClickListener listener) {
mListener = listener;
}
now you can call this method in your activity like this:
adapter.setOnItemClickListener(this); // implement interface
// or
adapter.setOnItemClickListener(new CustomItemClickListener());