ProgressBar while receiving Recyclerview data - android

I come to ask you for guidance with this, I have a recycler view, and what I want is that while the recyclerview is filled from the cloud firebase, a circular progressBar appears, and as soon as it loads, it disappears and the Recyclerview is loaded. I have already tried seeing various orientations around here but I cannot find it, with my code the progressbar is placed in a GONE way immediately, I imagine that you have to implement a ** CALLBACK ** or something like that, but no idea, I would appreciate that They will guide me a little with that of the CALLBACK, to see how I could implement it.
Borrow a photo and video from other users so they understand what I want to do
Demo Imagen ---> https://i.stack.imgur.com/JbLSi.png
Here is a video with what I want ---> Video
And here is the code that I am using
-------------------- Layout ------------------
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".MasvotingFragment">
<ProgressBar
android:id="#+id/progress_bar"
style="?android:progressBarStyle"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_gravity="center"/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="60dp"
android:visibility="gone"
android:layout_marginTop="5dp"
android:id="#+id/recyclerview_id">
</androidx.recyclerview.widget.RecyclerView>
</FrameLayout>
--------------------- Java ---------------------------
public class MasvotingFragment extends Fragment {
public MasvotingFragment() {
// Required empty public constructor
}
private FirebaseFirestore mDatabase;
private RecyclerView recyclerView ;
private Parcelable listState;
private RecyclerViewMasvotados mAdapter;
private ProgressBar mProgressBar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_masvoting, container, false);
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
mDatabase = FirebaseFirestore.getInstance();
recyclerView = view.findViewById(R.id.recyclerview_id);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mProgressBar = view.findViewById(R.id.progress_bar);
basedatocall();
if(listState!=null){
listState = Objects.requireNonNull(savedInstanceState).getParcelable("ListState");
}
}
private void basedatocall() {
Query query = mDatabase.collection("Post")
.orderBy("totales", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<masvotados> options = new FirestoreRecyclerOptions.Builder<masvotados>()
.setQuery(query, masvotados.class).build();
mAdapter = new RecyclerViewMasvotados(options);
mAdapter.notifyDataSetChanged();
recyclerView.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.GONE);
mAdapter.startListening();
recyclerView.setAdapter(mAdapter);
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onStart() {
super.onStart();
Objects.requireNonNull(recyclerView.getLayoutManager()).onRestoreInstanceState(listState);
mAdapter.startListening();
}
#Override
public void onStop() {
super.onStop();
if (mAdapter !=null){
mAdapter.stopListening();
}
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("ListState", Objects.requireNonNull(recyclerView.getLayoutManager()).onSaveInstanceState());
}
}
In advance Thank you all for your help, a hug

Related

Error: E/RecyclerView: No adapter attached; skipping layout on Fragments

I am trying to display a RecyclerView on a fragment using FireBase Database, but for some unknown reason its giving me this error: E/RecyclerView: No adapter attached; Im pretty sure im actually attaching the adapter, here's the code:
Main Activity
public class MainActivity extends AppCompatActivity {
Fragment currentFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null){
currentFragment = new MapsFragment();
changeFragment(currentFragment);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.menu_bookmarkList:
currentFragment = new ListaFragment();
break;
case R.id.menu_mapa:
currentFragment = new MapsFragment();
break;
}
changeFragment(currentFragment);
return super.onOptionsItemSelected(item);
}
private void changeFragment(Fragment currentFragment) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,currentFragment).commit();
}
}
ListaFragment (the one that should display the Recycler):
public class ListaFragment extends Fragment implements MyAdapter.RecyclerItemClick{
private MyAdapter myAdapter;
private RecyclerView recycler;
FirebaseDatabase database;
DatabaseReference myRef;
public ListaFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_lista, container, false);
database = FirebaseDatabase.getInstance();
myRef = database.getReference("Marcador");
recycler = (RecyclerView) v.findViewById(R.id.recyler);
recycler.setLayoutManager(new LinearLayoutManager(getContext()));
FirebaseRecyclerOptions<Marcador> options = new FirebaseRecyclerOptions.Builder<Marcador>()
.setQuery(myRef, Marcador.class).build();
myAdapter = new MyAdapter(options,this);
recycler.setAdapter(myAdapter);
return v;
}
#Override
public void onStart(){
super.onStart();
myAdapter.startListening();
}
#Override
public void onStop() {
super.onStop();
myAdapter.stopListening();
}
#Override
public void itemClick(Marcador marcador) {
}
}
And the adapter i've done (im skipping the xml's since they are quite simple):
public class MyAdapter extends FirebaseRecyclerAdapter<Marcador,MyAdapter.MarcadorHolder> {
private Context context;
private RecyclerItemClick itemClick;
public MyAdapter(#NonNull FirebaseRecyclerOptions<Marcador> options, RecyclerItemClick itemClick) {
super(options);
this.itemClick = itemClick;
}
#Override
protected void onBindViewHolder(#NonNull final MarcadorHolder holder, int position, #NonNull Marcador model) {
final Marcador marcador = getItem(position);
holder.textViewNom.setText(model.getNom());
holder.textViewLatitude.setText(String.valueOf(model.getLatitude()));
holder.textViewLongitude.setText(model.getLongitude());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemClick.itemClick(marcador);
}
});
}
#NonNull
#Override
public MarcadorHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recylcer_view_item,parent,false);
context = parent.getContext();
return new MarcadorHolder(v);
}
public class MarcadorHolder extends RecyclerView.ViewHolder{
TextView textViewNom;
TextView textViewLatitude;
TextView textViewLongitude;
public MarcadorHolder(#NonNull View itemView) {
super(itemView);
textViewNom = itemView.findViewById(R.id.textViewNom);
textViewLatitude = itemView.findViewById(R.id.textViewLatitud);
textViewLongitude = itemView.findViewById(R.id.textViewLongitut);
}
}
public interface RecyclerItemClick {
void itemClick(Marcador marcador);
}
}
I hope someone can give me an answer of why this is happening, since i've checked other options and i can't really get through it.
XML's attached of fragment:
<?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"
tools:context=".fragments.ListaFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyler"
android:layout_width="match_parent"
android:layout_height="545dp" />
</LinearLayout>
XML attached of item of recycler view:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="60dp" android:background="#CDCDCD" android:layout_marginBottom="5dp"
>
<TextView
android:id="#+id/textViewNom"
android:layout_width="410dp"
android:layout_height="55dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="5dp"
android:text="Title"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/textViewLatitud"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginTop="35dp"
android:text="latitud" />
<TextView
android:id="#+id/textViewLongitut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="125dp"
android:layout_marginTop="35dp"
android:text="longitut" />
<ImageView
android:id="#+id/imageView"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_marginLeft="265dp"
android:layout_marginTop="10dp"
/>
</RelativeLayout>
Do use below lines
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recycler.setLayoutManager(layoutManager);
recycler.setAdapter(adapter);
According to Fragment API Reference:
It is recommended to only inflate the layout in this method and move logic that operates on the returned View to onViewCreated(View, Bundle).
So in onCreateView you should only inflate your layout hence the View v = inflater.inflate(R.layout.fragment_lista, container, false); you used and move logic of your code to onViewCreated and the reason you facing E/RecyclerView: No adapter attached; is because you're trying to setting adapter for your recyclerview before even creation/inflation of the view which is failing to complete therefore after the creation/inflation is done there's no adapter attached to recyclerview.
It is generally recommended to not initialize the component using findViewById in onViewCreated() as per the The Google Developer Documents.
You should inflate your layout in onCreateView but shouldn't
initialize other views using findViewById in onCreateView.
Because in this method not every View is not Properly initialized. So, prefer to use onViewCreated() to get your view's Id and do setUp the UI.

Refreshing items as the user scrolls down in SwipeRefreshLayout

I have a SwipeRefreshLayout on my RecyclerView, I want the items to refresh as the user scrolls down instead of just pulling down from the top every time. I need something like Instagram or facebook that the posts load as the user is scrolling down. So that the user doesn't have to keep coming up again and again to refresh and load more posts
Here is my XML code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/bar">
</com.google.android.material.appbar.AppBarLayout>
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="#+id/swiperefresh"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/bar">
<androidx.core.widget.NestedScrollView
android:id="#+id/scrollview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/bar">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/bar"
android:id="#+id/recycler_view_posts"/>
</androidx.core.widget.NestedScrollView>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</RelativeLayout>
Here is my fragment code:
public class HomeFragment extends Fragment {
//POSTS
private RecyclerView recyclerViewPosts;
private PostAdapter postAdapter;
private List<Post> postLists;
private List<String> followingList;
private Context mContext;
private static final int TOTAL_NUMBER_OF_ITEMS_TO_LOAD = 5;
private SwipeRefreshLayout swipeRefreshLayout;
private int currentPage = 1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
//POSTS
recyclerViewPosts = view.findViewById(R.id.recycler_view_posts);
recyclerViewPosts.setHasFixedSize(true);
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerViewPosts.setLayoutManager(linearLayoutManager);
postLists = new ArrayList<>();
postAdapter = new PostAdapter(getContext(), postLists);
recyclerViewPosts.setAdapter(postAdapter);
swipeRefreshLayout = view.findViewById(R.id.swiperefresh);
checkFollowing();
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener(){
#Override
public void onRefresh() {
currentPage++;
postLists.clear();
readPosts();
}
});
return view;
}
private void readPosts() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");
Query postQuery = reference.limitToLast(currentPage * TOTAL_NUMBER_OF_ITEMS_TO_LOAD);
postQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
postLists.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Post post = snapshot.getValue(Post.class);
postLists.add(post);
}
postAdapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
I would recommend you to use the Paging Library from Android. It is design for it and you have a nice tutorial for it here. It might be a bit of work but it is worth it.

Items in RecyclerView in a Fragmnet don't appear

I saw there are similar post but my code is the same as the codes in the solutions so they weren't useful in my case. My app starts but and two tabs are shown. However the one that is supposed to show the items from a RecyclerView that's in it is empty.I also get this error:
E/RecyclerView: No adapter attached; skipping layout
So I have an Activity with a TabLayout and a ViewPager
public class MainActivity extends AppCompatActivity {
TabLayout tabLayout;
ViewPager viewPager;
PagerAdapter pagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabLayout=findViewById(R.id.tab_layout);
viewPager=findViewById(R.id.view_pager);
tabLayout.addTab(tabLayout.newTab().setText("CitiesFragment"));
tabLayout.addTab(tabLayout.newTab().setText("My CitiesFragment"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
pagerAdapter=new PagerAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
viewPager.setAdapter(pagerAdapter);
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) {
}
});
}
}
This is a fragment with only a RecyclerView in it
public class CitiesFragment extends Fragment {
RecyclerView recyclerView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View itemView = inflater.inflate(R.layout.cities_layout, container, false);
recyclerView = itemView.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
List<City> data = Database.getDatabase();
CitiesAdapter adapter = new CitiesAdapter(data);
recyclerView.setAdapter(adapter);
return itemView;
}
}
This is the XML for the fragment
<?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.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
And this is the Adapter
public class CitiesAdapter extends RecyclerView.Adapter<CitiesVIewHolder> {
List<City> data;
private int itemCount;
public CitiesAdapter(List<City> data) {
this.data = data;
itemCount=data.size();
}
#NonNull
#Override
public CitiesVIewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.city_layout, viewGroup, false);
CitiesVIewHolder viewHolder = new CitiesVIewHolder(itemView);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull CitiesVIewHolder citiesVIewHolder, int position) {
City city = data.get(position);
citiesVIewHolder.txtCityName.setText(city.getCityName());
citiesVIewHolder.txtCityInfo.setText(city.getCityInfo());
LoadImageTask loadImageTask = new LoadImageTask(citiesVIewHolder.imgCity);
loadImageTask.execute(city.getImageUrl());
}
#Override
public int getItemCount() {
return itemCount;
}
}
And the XML for the Adapter
<?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">
<ImageView
android:id="#+id/img_city"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/txt_city_name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/txt_city_info"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
My PagerAdapter only returns one of the two fragments(one of them is currently empty and the other on is with the RecyclerView)
public class PagerAdapter extends FragmentStatePagerAdapter {
private int itemCount;
public PagerAdapter(FragmentManager fm, int itemCount) {
super(fm);
this.itemCount = itemCount;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new CitiesFragment();
case 1:
return new MyCitiesFragment();
default:
return null;
}
}
#Override
public int getCount() {
return itemCount;
}
}
I am sorry for the code overload but I really can not understand what I'm doing wrong. Thanks for the help in advance.
First of all your adapter xml root LinearLayout has height set to match_parent so change that to wrap_content.
Second one override onViewCreated and there set recyclerView not in onCreateView. For example:
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setHasFixedSize(true);
List<City> data = Database.getDatabase();
CitiesAdapter adapter = new CitiesAdapter(data);
recyclerView.setAdapter(adapter);
}
Also consider adding line: recyclerView.setHasFixedSize(true);
E/RecyclerView: No adapter attached; skipping layout
TabLayout display fragment with recyclerView but fragment takes more time to load datasource that makes recycler created without adapter attached.
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View itemView = inflater.inflate(R.layout.cities_layout, container, false);
recyclerView = itemView.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
// List<City> data = Database.getDatabase(); // Don't fetch data on Main (UI) Thread
CitiesAdapter adapter = new CitiesAdapter(new ArrayList<City>()); //
recyclerView.setAdapter(adapter);
// Display city here one background and then update adapter.
return itemView;
}
If Datasource fetch data from local database then you can just use handler or postDelay on RecyclerView
recyclerView.postDelay(new Runnable(){
public void run(){
adapter.setCityList(result);
}
},500);
If you load data for server datasource the use background task, You can check this answer for fetch data from server with smooth way.
// load datasource inside Async Task.
new AsyncTaskHandler(new OnFinishCallback() {
#Override
public void onSuccess(List<City> result) {
adapter.setCityList(result);
}
}).execute("param that need to load datasource");
I have create a simple app to simulate your case.
RecyclerView width must be match_partent
<!--RecyclerView width must be match_parent-->
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content">
You can find the complete sample/CityPreview app on Github

Scroll the webPage Up and Down in RecyclerView in Android

I have implemented a webView within a recyclerView using Firebase as my database, but the problem is that the complete webPage is not visible, I cant scroll the web page up and down for the content and its stuck, I guess it is because of RecyclerView, please help so that I can scroll the page.
I am using Android Studio
webView class file:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview_page);
webVieRes = (RecyclerView) findViewById(R.id.resycleWeb);
mdataRef = FirebaseDatabase.getInstance().getReference().child("weber");
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<post2web,post2webViewHolder> firebaseRecyclerAdapte = new FirebaseRecyclerAdapter<post2web,post2webViewHolder>(
post2web.class,
R.layout.web_card,
post2webViewHolder.class,
mdataRef
) {
#Override
protected void populateViewHolder(post2webViewHolder viewHolder, post2web model, int position) {
viewHolder.setWebViewPost(model.getWebViewPost());
}
};
webVieRes.setAdapter(firebaseRecyclerAdapte);
}
public static class post2webViewHolder extends RecyclerView.ViewHolder {
View mVie;
public post2webViewHolder(View itemView) {
super(itemView);
mVie = itemView;
}
public void setWebViewPost(String webViewPost) {
WebView post_web = (WebView) mVie.findViewById(R.id.webView_news);
post_web.loadUrl(webViewPost);
post_web.setWebViewClient(new WebViewClient());
}
}
RecyclerView xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="android.support.v7.widget.LinearLayoutManager"
android:id="#+id/resycleWeb"/>
</LinearLayout>

Layout for tablets using two fragments

I am doing a sample project as an excercise and want to display two fragments in the same activity when dealing with tablets(7' and 10').
So what I have so far is this.
As you can see I can display the data of my recyclerview in the left (static) fragment. However the right fragment is empty.
So I have two questions.
1) How to display by default in the right fragment the data of the first row of recyclerview?(ie image and article)
2) How to implement the click listener and update the right fragment?
Here is my code:
MainActivity
public class MainActivity extends AppCompatActivity {
private boolean mTwoPane;
private static final String DETAIL_FRAGMENT_TAG = "DFTAG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(findViewById(R.id.detailed_match_reports)!=null) {
mTwoPane = true;
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.detailed_match_reports, new DetailedActivityFragment(),DETAIL_FRAGMENT_TAG)
.commit();
}else{
mTwoPane = false;
}
}
}
}
layout/activity_main.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/match_reports"
android:name="theo.testing.androidservices.fragments.MainActivityFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
tools:context="theo.testing.androidservices.activities.MainActivity"
tools:layout="#android:layout/list_content" />
layout-sw600dp/activity_main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false"
android:divider="?android:attr/dividerHorizontal"
android:orientation="horizontal"
tools:context="theo.testing.androidservices.activities.MainActivity">
<fragment
android:id="#+id/match_reports"
android:name="theo.testing.androidservices.fragments.MainActivityFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
tools:layout="#android:layout/list_content" />
<FrameLayout
android:id="#+id/detailed_match_reports"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="4" />
</LinearLayout>
MainActivityFragment
public class MainActivityFragment extends Fragment {
public static final String TAG = "AelApp";
public static ArrayList<MyModel> listItemsList;
RecyclerView myList;
public static MatchReportsAdapter adapter;
public MainActivityFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
updateMatchReport();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
getActivity().setTitle("Match Report");
View rootView = inflater.inflate(R.layout.fragment_main_activity, container, false);
listItemsList = new ArrayList<>();
myList = (RecyclerView)rootView.findViewById(R.id.listview_match_reports);
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
myList.setHasFixedSize(true);
myList.setLayoutManager(linearLayoutManager);
adapter = new MatchReportsAdapter(getActivity(), listItemsList);
myList.setAdapter(adapter);
return rootView;
}
public void updateMatchReport(){
Intent i = new Intent(getActivity(), MatchReport.class);
getActivity().startService(i);
}
}
First let me answer the second question. To show a fragment on the right side of the screen add something like this (note how I'm using that id of the frame layout to replace the fragment):
Fragment fragment = new MyRightSideFragment();
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.detailed_match_reports, fragment).commit();
Now, for the first question, you need to implement click listener, you can find an example here.
public class ReactiveAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (Integer)v.getTag();
showDetail(position);
}
});
}
}
Notice that I'm using the tag of the view to identify the position (so somwhere in your onBindViewHolder code you must set this tag).
public function showDetail(int position) {
... show fragment por position
}
and finally, when your in your OnCreateView or somewhere in your setup code, call showDetail(0).

Categories

Resources