Call a function in surfaceview class from a fragment in android - android-fragments

I have a surfaceview class in which there is a method updateValue(). This surface view is inside a fragment(framelayout). I am trying to call the method updateValue() from the fragment class. But it is not working.
public class ImageSurface extends SurfaceView implements SurfaceHolder.Callback {
......
public void updateValue(int message){
.......
}
}
xml file in which this surfaceview is declared.
fragment_main.xml --->
<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.paint.drawx.MainActivity$PlaceholderFragment" >
<com.paint.drawx.ImageSurface
android:id ="#+id/imagesurface1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
activity_main.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="#+id/container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
</FrameLayout>
<fragment android:name="com.paint.drawx.DrawTools"
android:id="#+id/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#FF889911"
/>
</android.support.v4.widget.DrawerLayout>
fragment class ----
public static class PlaceholderFragment extends Fragment {
ImageSurface imageSurface;
public PlaceholderFragment() {
//imageSurface = (ImageSurface)findViewById(R.id.imagesurface1);
}
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
imageSurface = (ImageSurface)activity.findViewById(R.id.imagesurface1);
}
public void setMessage(int mess){
try{
imageSurface.updateValue(mess);////////this is not working. gives error nullpoint exception
}catch(Exception e){
Log.d("error","is"+e.toString());
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
setRetainInstance(true);
return rootView;
}
}
in the above class there is a method setMessage from which i call the method updateValue of the ImageSurface class but it gives null point exception. what am i doing wrong .
Thanks in advance.

I removed this line from onAttach() method
imageSurface = (ImageSurface)activity.findViewById(R.id.imagesurface1);
and inserted this line in onCreateView()
imageSurface = (ImageSurface) rootView.findViewById(R.id.imagesurface1);
and every thing is fine

Related

I want an implit loading spinner to be displayed in a fragment which has some views and the user clicks any one of them

I have a fragment which basically has a recyclerView. So when the user clicks on any item of the view, the background needs to change (the item clicked needs to be highlighted) and a loading spinner needs to appear and then fragment needs to replaced based on the item clicked. How to achieve this? In the below code, I have implemented the highlight facility, but once an item is clicked redirection should happen....
My Internal Layout, (layout_research)
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="wrap_content"
android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools"
app:cardCornerRadius="#dimen/loginCardRadius"
android:elevation="5dp"
android:layout_gravity="center"
android:layout_marginTop="#dimen/loginViewsMargin"
android:layout_marginBottom="#dimen/loginViewsMargin"
android:background="#ffffff">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_gravity="center"
android:padding="#dimen/loginViewsMargin">
<ImageView
android:contentDescription="#string/abc"
android:src="#drawable/logo"
android:layout_gravity="center"
android:layout_height="100dp"
android:layout_width="wrap_content"
android:layout_marginTop="#dimen/loginViewsMargin"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/grid_view"
android:layout_marginTop="20dp"
tools:listitem="#layout/row_item"
android:layout_gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
app:spanCount="2"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
My External Layout,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_height="match_parent"
android:layout_width="match_parent">
<ScrollView
android:fillViewport="true"
android:layout_height="match_parent"
android:layout_width="match_parent">
<RelativeLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_alignParentTop="true"
android:baselineAligned="true"
android:weightSum="12"
android:background="#drawable/login_shape_bk"
android:orientation="vertical"
android:layout_weight="3">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/ic_login_bk" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:orientation="vertical"
android:layout_marginTop="40dp"
android:layout_marginRight="30dp"
android:layout_marginLeft="30dp">
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:textColor="#ffffff"
android:textSize="22sp"
android:textStyle="bold"
android:layout_marginTop="20dp"
android:gravity="center"
android:layout_gravity="center"
android:text="#string/abcd"/>
<include
layout="#layout/internal_research"/>
</LinearLayout>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
My Java File,
package com.example.a123;
import android.os.Bundle;
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.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class research extends Fragment {
int selectedPosition=-1;
private String[] names = {"Blogs & Books","Patents","Projects","Publications"};
private int[] image ={R.drawable.books,R.drawable.patents,R.drawable.project,R.drawable.publications};
private ArrayList<adapter_for_research> mProfiles;
private RecyclerView mProfileRecyclerView;
#Override
public void onCreate(Bundle savedInstanceState) {
mProfiles = new ArrayList<>();
for(int i =0;i<names.length;i++){
adapter_for_research s = new adapter_for_research();
s.setname(names[i]);
s.setImageId(image[i]);
mProfiles.add(s);
}
setRetainInstance(true);
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_research, container, false);
mProfileRecyclerView = view.findViewById(R.id.grid_view);
updateUI();
return view;
}
private void updateUI(){
ProfileAdapter mAdapter = new ProfileAdapter(mProfiles);
mProfileRecyclerView.setAdapter(mAdapter);
}
private class ProfileHolder extends RecyclerView.ViewHolder {
private adapter_for_research mProfilecsg;
private ImageView mImageView;
private TextView mnameTextView;
private ProfileHolder(final View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.image_view);
mnameTextView = itemView.findViewById(R.id.text_view);
}
private void bindData(adapter_for_research s){
mProfilecsg = s;
mImageView.setImageResource(s.getImageId());
mnameTextView.setText(s.getname());
}
}
private class ProfileAdapter extends RecyclerView.Adapter<ProfileHolder>{
private ArrayList<adapter_for_research> mProfiles;
private ProfileAdapter(ArrayList<adapter_for_research> profile){
mProfiles = profile;
}
#NonNull
public ProfileHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.row_item,parent,false);
return new ProfileHolder(view);
}
#Override
public void onBindViewHolder(ProfileHolder holder, final int position) {
adapter_for_research s = mProfiles.get(position);
holder.bindData(s);
if(selectedPosition==position)
holder.itemView.setBackground(ContextCompat.getDrawable(getContext(),R.drawable.item_select));
else
holder.itemView.setBackground(ContextCompat.getDrawable(getContext(),R.drawable.item_nselect));
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectedPosition=position;
notifyItemChanged(selectedPosition);
}
});
}
#Override
public int getItemCount() {
return mProfiles.size();
}
}
}
Adapter Class,
package com.example.a123;
class adapter_for_research {
private String mName;
private int mImageId;
String getname() {
return mName;
}
void setname(String mName) {
this.mName = mName;
}
int getImageId() {
return mImageId;
}
void setImageId(int mImageId) {
this.mImageId = mImageId;
}
}

NullPointerException while populating views inside populateView using FirebaseListAdapter even when everything's right

The populateView method of FirebaseListAdapter is throwing null pointer exceptions while trying to set text of individual text views even though the layout id, view ids are correct. Here's the main activity
public class MainActivity extends AppCompatActivity {
private String dbUrlString = "MY_DB_URL_HERE";
private ListView listView;
private DatabaseReference databaseReference;
private FirebaseListAdapter<Video> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(getApplicationContext(),"Fetching",Toast.LENGTH_SHORT).show();
databaseReference = FirebaseDatabase.getInstance().getReferenceFromUrl(dbUrlString);
listView = (ListView) findViewById(R.id.list_view);
FirebaseListOptions<Video> options = new FirebaseListOptions.Builder<Video>()
.setQuery(databaseReference,Video.class)
.setLayout(R.layout.custom_item_layout)
.build();
adapter = new FirebaseListAdapter<Video>(options) {
#Override
protected void populateView(#NonNull View v, #NonNull final Video video, int position) {
TextView vname = (TextView) findViewById(R.id.video_name);
TextView vId = (TextView) findViewById(R.id.video_list_id);
vname.setText(video.getName());
vId.setText(video.getVideoId());
}
};
listView.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
This is the main layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
These are the views in the custom_item_layout file with the respective ids:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_height="wrap_content"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:weightSum="10"
android:layout_margin="10dp">
<ImageView
android:id="#+id/play_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_play_video_24dp"
android:layout_marginRight="10dp"
android:layout_centerInParent="true"
android:layout_alignParentLeft="true"/>
<TextView
android:id="#+id/video_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/play_icon"
android:text="Video title"
android:textSize="20sp"
android:layout_centerInParent="true"
android:textColor="#android:color/black"/>
<TextView
android:id="#+id/video_list_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="."
android:layout_alignParentRight="true"
android:layout_centerInParent="true"/>
</RelativeLayout>
This is the Video class:
package com.example.util;
public class Video {
private String name, videoId;
public Video(){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVideoId() {
return videoId;
}
public void setVideoId(String videoId) {
this.videoId = videoId;
}
public Video(String name, String videoId) {
this.name = name;
this.videoId = videoId;
}
}
And this is the error I'm getting:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.gifapplication.MainActivity$1.populateView(MainActivity.java:44)
at com.example.gifapplication.MainActivity$1.populateView(MainActivity.java:39)
at com.firebase.ui.database.FirebaseListAdapter.getView(FirebaseListAdapter.java:121)
at android.widget.AbsListView.obtainView(AbsListView.java:2365)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1408)
at android.widget.ListView.onMeasure(ListView.java:1315)
at android.view.View.measure(View.java:22759)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6788)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514)
at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1167)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:687)
at android.view.View.measure(View.java:22759)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6788)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143)
at android.view.View.measure(View.java:22759)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6788)
at androidx.appcompat.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:403)
at android.view.View.measure(View.java:22759)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6788)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:22759)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6788)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:806)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:685)
at android.view.View.measure(View.java:22759)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6788)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at com.android.internal.policy.DecorView.onMeasure(DecorView.java:754)
at android.view.View.measure(View.java:22759)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2538)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1565)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1833)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1453)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7039)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:924)
at android.view.Choreographer.doCallbacks(Choreographer.java:732)
at android.view.Choreographer.doFrame(Choreographer.java:664)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:910)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6524)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:888)
Any help is appreciated. I've been going crazy trying to fix this. Tried a couple of fixes suggested online but nothing works. I don't even get why the views are null even when they're being instantiated with the right ids.

Blank screen when trying to implement MVVM / ViewModel and data binding architecture

I am trying to implement the Model-View-ViewModel architectural pattern and XML data binding in my Android Java app. The code seems all correct as far as I can see, however I'm getting a blank screen when I run the app (not even the bottomNavigationView is showing). I am using a ViewModel to store/persist data for a fragment called AllTimeBestFragment. Specifically, AllTimeBestFragment is one of three fragments in a Viewpager-tabLayout.
Would appreciated any insight into what I'm doing wrong!
AllTimeBestFragment
public class AllTimeBestFragment extends Fragment {
private ImageViewCallback imageViewCallback;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(Constants.SkiCompanionDebug, "AllTimeBestFragment");
bindToViewModel();
return inflater.inflate(R.layout.fragment_all_time_best, container, false);
}
//imageview callback
#Override
public void setUserVisibleHint(boolean visible) {
super.setUserVisibleHint(visible);
imageViewCallback.setImage(R.drawable.all_time_best);
}
public void addCallback(ImageViewCallback imageViewCallback) {
this.imageViewCallback = imageViewCallback;
}
//binding the view (fragment) to the asoociated viewModel
public void bindToViewModel(){
FragmentAllTimeBestBinding binding = DataBindingUtil.setContentView(getActivity(), R.layout.fragment_all_time_best);
AllTimeBestViewModel viewModel = ViewModelProviders.of(this).get(AllTimeBestViewModel.class);
AllTimeStats allTimeStats = BCCDatabase.getInstance(getActivity()).getAllTimeStats();
viewModel.init(allTimeStats);
binding.setAllTimeBestViewModel(viewModel);
}
}
AllTimeBestViewModel
public class AllTimeBestViewModel extends ViewModel {
private AllTimeStats allTimeStats;
public void init(AllTimeStats allTimeStats) {
this.allTimeStats = allTimeStats;
}
public String getDurationTotal(){
return ""+allTimeStats.getDurationTotal();
}
}
fragment_all_time_best.xml
<data>
<variable
name="allTimeBestViewModel"
type="skicompanion.skicompanion.viewmodels.AllTimeBestViewModel" />
</data>
<ScrollView 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:id="#+id/track_scrollview"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:context="skicompanion.skicompanion.fragments.AllTimeBestFragment">
<android.support.v7.widget.CardView
android:id="#+id/duration_cardview"
android:layout_width="match_parent"
android:layout_height="180dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/duration_total"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{allTimeBestViewModel.durationTotal}"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="#+id/duration_total_tv"
app:layout_constraintStart_toStartOf="#+id/imageView2"
app:layout_constraintTop_toBottomOf="#+id/duration_total_tv" />
...
...
...
Gradle
implementation "android.arch.lifecycle:extensions:1.1.1"
implementation "android.arch.lifecycle:viewmodel:1.1.1"
I found the answer here: How to use data-binding with Fragment
I was binding the data as if I were dealing with an activity - I needed to bind it for a fragment instead. The trick was to use DataBindingUtil.inflate rather than DataBindingUtil.setContentView. Below is the correct code snippet:
public class AllTimeBestFragment extends Fragment {
private ImageViewCallback imageViewCallback;
private FragmentAllTimeBestBinding binding;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(Constants.SkiCompanionDebug, "AllTimeBestFragment");
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_all_time_best, container, false);
bindToViewModel();
return binding.getRoot();
}
//imageview callback
#Override
public void setUserVisibleHint(boolean visible) {
super.setUserVisibleHint(visible);
imageViewCallback.setImage(R.drawable.all_time_best);
}
public void addCallback(ImageViewCallback imageViewCallback) {
this.imageViewCallback = imageViewCallback;
}
//binding the view (fragment) to the asoociated viewModel
public void bindToViewModel(){
AllTimeBestViewModel viewModel = ViewModelProviders.of(this).get(AllTimeBestViewModel.class);
AllTimeStats allTimeStats = BCCDatabase.getInstance(getActivity()).getAllTimeStats();
viewModel.init(allTimeStats);
binding.setAllTimeBestViewModel(viewModel);
}
}

In Android, how to replace a Fragment in a Tablayout?

For the love of god, I can't seem to figure this out. I have a tablayout with 3 tabs (each tab has in it a fragment). All i want to do is on the second fragment, the user clicks a button, and it replaces the second tab's fragment with a new fragment. So how do I go about doing that?
Here is my xml for the fragment I want to replace .
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragCards_mainLL">
<android.support.v4.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="24dp"
android:id="#+id/fragCards_LL">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/fragCards_RecyclerView">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</FrameLayout>
And here is the fragment I want to replace the second tab's fragment.
<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="com.daprlabs.swipedeck.ProfileView.FragmentFollowers"
android:id="#+id/fragFollowrs_mainFL">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Followers Fragment"
android:gravity="center"
android:textSize="30dp"/>
</FrameLayout>
Here is my viewpageAdapter code
public class ViewPagerAdapter extends FragmentPagerAdapter
{
ArrayList<Fragment> fragments = new ArrayList<>();
ArrayList<String> tabTitles = new ArrayList<>();
public ViewPagerAdapter(android.support.v4.app.FragmentManager fragmentManager)
{
super(fragmentManager);
}
#Override
public Fragment getItem(int position)
{
return fragments.get(position);
}
#Override
public int getCount()
{
return fragments.size();
}
#Override
public CharSequence getPageTitle(int position)
{
return tabTitles.get(position);
}
public void addFragments(Fragment fragment, String titles)
{
this.fragments.add(fragment);
this.tabTitles.add(titles);
}
}
Now somewhere in my Tab 2 fragment I have an onClickListener, I need to replace the entire fragment with a new fragment. I am not sure what to put in here...Currently, my "Followers Fragment" just goes beneath my recyclerview, so I can still see the views in the current, so it doesn't entirely replace the fragment...
#Override
public void onClick(View v)
{
FragmentFollowers f1 = new FragmentFollowers();
android.support.v4.app.FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragCards_LL,f1);
fragmentTransaction.setTransition(android.support.v4.app.FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
Toast.makeText(getActivity(),"position " +position,Toast.LENGTH_SHORT).show();
}

Replace one fragment to another fragment in the swipable TabHost

I have an activity extending fragment activity and swipable tab view. In tab view i have used fragment and Tabs pager adapter to call fragments according to the tab position.
Now i want to replace these fragment using on click items with another fragment and on back press i want the original fragment back...
But when i am clicking on the items..it do nothing...
What should i do..pls help me ...
Thanks in advance
here is my code-
This is my Homeactivity which has tab
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_screen);
ressources = getResources();
mViewPager = (ViewPager) findViewById(R.id.viewpager);
// Tab Initialization
initialiseTabHost();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
// Fragments and ViewPager Initialization
mViewPager.setAdapter(mAdapter);
mViewPager.setOnPageChangeListener(HomeScreen.this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
// Method to add a TabHost
private static void AddTab(HomeScreen activity, TabHost tabHost,
TabHost.TabSpec tabSpec) {
tabSpec.setContent(new MyTabFactory(activity));
tabHost.addTab(tabSpec);
}
// Manages the Tab changes, synchronizing it with Pages
public void onTabChanged(String tag) {
int pos = this.mTabHost.getCurrentTab();
this.mViewPager.setCurrentItem(pos);
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
// Manages the Page changes, synchronizing it with Tabs
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
int pos = this.mViewPager.getCurrentItem();
this.mTabHost.setCurrentTab(pos);
}
#Override
public void onPageSelected(int arg0) {
}
// Tabs Creation
private void initialiseTabHost() {
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
// TODO Put here your Tabs
HomeScreen.AddTab(
this,
this.mTabHost,
this.mTabHost.newTabSpec(Button_tab).setIndicator("",
ressources.getDrawable(R.drawable.menu)));
HomeScreen.AddTab(this, this.mTabHost,
this.mTabHost.newTabSpec(Image_tab).setIndicator("",ressources.getDrawable(R.drawable.jobs)));
HomeScreen.AddTab(this, this.mTabHost,
this.mTabHost.newTabSpec(Text_tab).setIndicator("",ressources.getDrawable(R.drawable.people)));
HomeScreen.AddTab(this, this.mTabHost,
this.mTabHost.newTabSpec("line_tab").setIndicator("",ressources.getDrawable(R.drawable.calenders)));
mTabHost.setOnTabChangedListener(this);
}
#Override
public void onBackPressed() {
boolean isPopFragment = false;
String currentTabTag = mTabHost.getCurrentTabTag();
if (currentTabTag.equals(Button_tab)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(Button_tab)).popFragment();
} else if (currentTabTag.equals(Image_tab)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(Image_tab)).popFragment();
} else if (currentTabTag.equals(Text_tab)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(Text_tab)).popFragment();
} else if (currentTabTag.equals(line_tab)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(line_tab)).popFragment();
}
if (!isPopFragment) {
finish();
}
}
My XMl for HomeActivity:
<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=".HomeScreen" >
<RelativeLayout
android:id="#+id/header"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="10dp"
android:orientation="horizontal" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:src="#drawable/krma" />
<Button
android:layout_width="30dp"
android:layout_marginTop="3dp"
android:layout_height="30dp"
android:layout_marginRight="10dp"
android:layout_alignParentRight="true"
android:background="#drawable/listmenu" />
</RelativeLayout>
<TabHost
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_weight="0"
android:background="#FF7519"
android:orientation="horizontal" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom" />
</LinearLayout>
</TabHost>
</RelativeLayout>
My TabsPagerAdapter is :
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new Menu();
case 1:
return new Jobs();
case 2:
return new Applicant();
case 3:
return new Admin();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 4;
}
}
my Job fragment is :
public class Jobs extends BaseContainerFragment implements OnItemClickListener {
ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_job, container,
false);
listView = (ListView) rootView.findViewById(R.id.list);
SharedPreferences sharedpreferences = getActivity()
.getSharedPreferences(LoginScreen.MyPREFERENCES,
Context.MODE_PRIVATE);
String loggedInEmail = sharedpreferences.getString("nameKey", "");
// String loggedInEmail="aditya.pratap#krmaa.com";
RestClient client = new RestClient(
"http://122.180.4.83:8080/krmaa/krmaa/joblist/" + loggedInEmail
+ "/1234");
client.AddHeader("GData-Version", "2");
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
String response = client.getResponse();
Gson gson = new Gson();
String convertedStr = response.replace("\\\"", "\"");
String finalJson = convertedStr.substring(1, convertedStr.length() - 2);
JobDTO[] jobDTOList = gson.fromJson(finalJson, JobDTO[].class);
ItemAdapter adapter = new ItemAdapter(getActivity()
.getApplicationContext(), jobDTOList);
// Attach the adapter to a ListView
ListView listView = (ListView) rootView.findViewById(R.id.list);
listView.setAdapter(adapter);
// return list of jobDTO and iterate in view page.
return rootView;
}
public class JobDTOList {
List<JobDTO> jobDTOList;
public List<JobDTO> getJobDTOList() {
return jobDTOList;
}
public void setJobDTOList(List<JobDTO> jobDTOList) {
this.jobDTOList = jobDTOList;
}
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Here I want to switch from 1st Tab(Fragment1) to 2nd Tab(Fragment2)
// How can I switch from 1st tab to 2nd tab here???
// Below code is not worked for me.
fragment2 fr = new fragment2();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.job,fr);
transaction.commit();
}
}
My xml for Job fragment is :
<?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:id="#+id/job"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentTop="true"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="6"
android:background="#A3A385"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingTop="10dp"
android:text="Jobs"
android:textColor="#000000"
android:textSize="10pt" />
<Button
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:layout_weight="1"
android:background="#A3A385"
android:text="Filter"`enter code here`
android:onClick="frag"
android:textSize="10pt" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >`enter code here`
<ListView`enter code here`
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</ListView>
</LinearLayout>
</LinearLayout>

Resources