ViewPager2 main activit toolabar is not working - android

i want to press my custom toolbar button in view activity but i can't do it
how can i bring my custom toolbar on ViewActivity?
pls help me
here is my activity_view
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appbarLayout"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:elevation="0dp"
app:layout_constraintTop_toTopOf="parent">
<androidx.appcompat.widget.Toolbar
android:id="#+id/alarmToolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_gravity="center"
app:contentInsetStart="0dp"
app:menu="#menu/alarm_title">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="미운 오리 새끼"
android:fontFamily="#font/applesdgothicneoeb"
android:textColor="#color/black"
android:textSize="25sp" />
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
here is my ViewActivity
package com.example.test;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;
import java.util.ArrayList;
import java.util.List;
public class ViewActivity extends AppCompatActivity {
private ViewPager2 pager;
private FragmentStateAdapter pagerAdapter;
private ZoomOutPageTransformer pageTransformer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
Toolbar toolbar = findViewById(R.id.alarmToolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
List<Fragment> fragments = new ArrayList<>();
fragments.add(new Duck1Fragment());
fragments.add(new Duck2Fragment());
fragments.add(new Duck3Fragment());
pager = findViewById(R.id.pager);
pagerAdapter = new PagerAdapter(this, fragments);
pager.setAdapter(pagerAdapter);
pager.setPageTransformer(pageTransformer);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.alarm_title, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.close:
finish();
return true;
default:
return super .onOptionsItemSelected(item);
}
}
}
here is my Duck1Activity
<?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"
xmlns:tools="http://schemas.android.com/tools" >
<ImageView
android:id="#+id/imageView"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_marginTop="70dp"
android:src="#drawable/tale_character"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<FrameLayout
android:id="#+id/frameLayout"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_marginTop="150dp"
android:background="#drawable/background"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.495"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="161dp"
app:layout_constraintTop_toTopOf="parent">
<ImageView
android:id="#+id/ducktale_image"
android:layout_width="275dp"
android:layout_height="275dp"
android:layout_gravity="center"
tools:srcCompat="#tools:sample/avatars" />
</FrameLayout>
<FrameLayout
android:layout_width="300dp"
android:layout_height="175dp"
android:layout_marginBottom="50dp"
android:background="#drawable/background"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.495"
app:layout_constraintStart_toStartOf="parent">
<TextView
android:id="#+id/duck_tale"
android:layout_width="275dp"
android:layout_height="150dp"
android:scrollbars="vertical"
android:layout_gravity="center"
android:fontFamily="#font/applesdgothicneoeb"
android:text="안녕하세요 이것은 테스트입니다."
android:textAlignment="center"
android:textSize="25sp" />
</FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
here is my duckFragment
package com.example.test;
import static android.speech.tts.TextToSpeech.ERROR;
import android.content.Context;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toolbar;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import java.util.Locale;
public class Duck1Fragment extends Fragment {
private TextToSpeech tts;
private TextView duck;
Context ct;
public Duck1Fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_duck1, container, false);
ct = getActivity().getApplication();
ImageView duck_image = (ImageView) rootView.findViewById(R.id.ducktale_image);
TextView duck = (TextView) rootView.findViewById(R.id.duck_tale);
duck.setText(
);
duck.setMovementMethod(new ScrollingMovementMethod());
tts = new TextToSpeech(ct, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != ERROR) {
tts.setLanguage(Locale.KOREAN);
}
}
});
duck_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tts.setSpeechRate(1.0f);
tts.speak(duck.getText().toString(), TextToSpeech.QUEUE_FLUSH, null);
}
});
return rootView;
}
}
here is my PageAdapter
package com.example.test;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import java.util.List;
public class PagerAdapter extends FragmentStateAdapter {
private List<Fragment> fragments;
private static final int NUM_PAGES = 3;
public PagerAdapter(FragmentActivity fragmentActivity, List<Fragment> fragments) {
super(fragmentActivity);
this.fragments = fragments;
}
#NonNull
#Override
public Fragment createFragment(int position) { [tag:tag-name]
if (position == 0) return new Duck1Fragment();
else if (position == 1) return new Duck2Fragment();
else return new Duck3Fragment();
}
#Override
public int getItemCount() {
return NUM_PAGES;
}
}
i want to press my custom button on toolbar..
so u guys can help me?
i serched for google and chatgpt but i cant solve it

Related

ViewPager on TabLayout not Showing?

I am just doing my Daily practice and I had a Problem. I've created Viewpager on Tab Layout but it not worked.
I don't know why, I am just doing like the tutorial on the internet and spend for this problem 2 days. :/
The Tablayout showing all tabs but not with the view (fragment tab).
I'll thank for any help from you all :))))))))
So, here's what I code,
content_home.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView 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/content_home"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".ui.home.ViewPagerActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.tabs.TabLayout
android:id="#+id/content_home_tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabBackground="#color/colorPrimaryAlternate"
app:tabGravity="fill"
app:tabMode="fixed"
app:tabIndicatorColor="#color/colorPrimary"
app:tabSelectedTextColor="#color/colorPrimary"
app:tabTextColor="#color/colorPrimaryDarkAlternate"
app:tabIconTint="#color/tab_color_selector"
app:tabTextAppearance="#style/tabAllCaps">
<com.google.android.material.tabs.TabItem
android:id="#+id/tab1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:icon="#drawable/ic_waterpark"
android:text="#string/waterpark" />
<com.google.android.material.tabs.TabItem
android:id="#+id/tab2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:icon="#drawable/ic_home_black_24dp"
android:text="#string/drypark" />
<com.google.android.material.tabs.TabItem
android:id="#+id/tab3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:icon="#drawable/ic_human_male_female"
android:text="#string/facilities" />
</com.google.android.material.tabs.TabLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/content_home_viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/content_home_tablayout"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_alignParentBottom="true" />
</LinearLayout>
</androidx.core.widget.NestedScrollView>
ViewPagerActivity:
package com.ardityo.android.transeraapps.ui.home;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import com.ardityo.android.transeraapps.R;
import com.ardityo.android.transeraapps.ui.home.tabs.drypark.DryParkFragment;
import com.ardityo.android.transeraapps.ui.home.tabs.facilities.FacilitiesFragment;
import com.ardityo.android.transeraapps.ui.home.tabs.waterpark.WaterParkFragment;
import com.google.android.material.tabs.TabLayout;
public class ViewPagerActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
ViewPagerAdapter adapter;
WaterParkFragment waterParkFragment;
DryParkFragment dryParkFragment;
FacilitiesFragment facilitiesFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_home);
viewPager = (ViewPager) findViewById(R.id.content_home_viewpager);
viewPager.setOffscreenPageLimit(3);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.content_home_tablayout);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager)
{
adapter = new ViewPagerAdapter(getSupportFragmentManager());
// waterParkFragment=new WaterParkFragment();
// dryParkFragment=new DryParkFragment();
// facilitiesFragment=new FacilitiesFragment();
// adapter.addFragment(waterParkFragment,"WaterPark");
// adapter.addFragment(dryParkFragment,"DryPark");
// adapter.addFragment(facilitiesFragment.newInstance(),"Facilities");
adapter.addFragment(WaterParkFragment.newInstance(),"WaterPark");
adapter.addFragment(DryParkFragment.newInstance(),"DryPark");
adapter.addFragment(FacilitiesFragment.newInstance(),"Facilities");
viewPager.setAdapter(adapter);
}
}
DryParkFragment (Same with WaterParkFragment & FacilitiesFragment):
package com.ardityo.android.transeraapps.ui.home.tabs.drypark;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.ardityo.android.transeraapps.R;
import com.ardityo.android.transeraapps.ui.settings.SettingsViewModel;
public class DryParkFragment extends Fragment {
public DryParkFragment() {
// Required empty public constructor
}
public static DryParkFragment newInstance() {
Bundle args = new Bundle();
DryParkFragment fragment = new DryParkFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.content_home_2, container, false);
}
// #Override
// public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// inflater.inflate(R.menu.menu_calls_fragment, menu);
// super.onCreateOptionsMenu(menu, inflater);
// }
}
content_home_2.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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".ui.home.tabs.drypark.DryParkFragment"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/mascot_head" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test" />
</LinearLayout>
The problem comes from using ViewPager inside NestedScrollView . This may also happen when you use CoordinatorLayout . You have two options to achieve that .
1 . ViewPager2 :
The first option is to use ViewPager2 . Just take a look :
https://developer.android.com/jetpack/androidx/releases/viewpager2
2 . Use custom ViewPager :
Here is a class for you that can determine its height based on childs.
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import androidx.viewpager.widget.ViewPager;
public class CustomViewPager extends ViewPager {
public CustomViewPager(Context context) {
super(context);
}
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int biggestHeightMeasureSpec = 0;
for(int i = 0 ; i < getChildCount() ; i++)
{
View child = getChildAt(i);
if (child != null) {
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int h = child.getMeasuredHeight();
heightMeasureSpec = MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY);
if(heightMeasureSpec > biggestHeightMeasureSpec)
biggestHeightMeasureSpec = heightMeasureSpec;
}
}
super.onMeasure(widthMeasureSpec, biggestHeightMeasureSpec);
}
}
Finally just use it in your XML layout :
<PATH.TO.YOUR.CustomViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Try using viewpager 2, dont forget to use newest library
-> https://developer.android.com/jetpack/androidx/releases/viewpager2?hl=id

HTML Not Showing in Webview

I am trying to display some HTML in a webview within a fragment and it is not showing up. I used the same code in a different application and it works but it's not working in this case. I am at a loss. I'm not getting any errors, the HTML is just not displayed. I can see that the webview is appearing. The following is my fragment, layout file, and activity utilizing the fragment.
package com.siemens.google_glass_ict21_app.wirefragments;
import android.graphics.Color;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.TextView;
import com.siemens.google_glass_ict21_app.R;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Base64;
import java.util.Scanner;
/**
* A simple {#link Fragment} subclass.
* Use the {#link GrommetFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class GrommetFragment extends BaseWireFragment {
private static final String TITLE_KEY = "title_key";
private static final String DESCRIPTION_KEY = "description_key";
private static final String WEBVIEW_KEY = "webview_key";
public static GrommetFragment newInstance(String title, String description, String webView) {
GrommetFragment fragment = new GrommetFragment();
Bundle args = new Bundle();
args.putString(TITLE_KEY, title);
args.putString(DESCRIPTION_KEY, description);
args.putString(WEBVIEW_KEY, webView);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.grommet_fragment, container, false);
if(getArguments() != null){
final TextView textView = view.findViewById(R.id.textView3);
textView.setText(getArguments().getString(TITLE_KEY,""));
final TextView description = view.findViewById(R.id.textView2);
description.setText(getArguments().getString(DESCRIPTION_KEY, ""));
WebView webView = (WebView) view.findViewById(R.id.webview);
String unencodedHtml = getArguments().getString(WEBVIEW_KEY, "");
String encodedHtml = Base64.getEncoder().encodeToString(unencodedHtml.getBytes());
webView.loadData(encodedHtml, "text/html", "base64");
webView.setBackgroundColor(Color.TRANSPARENT);
}
// Inflate the layout for this fragment
return view;
}
}
<?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=".wirefragments.GrommetFragment">
<WebView
android:id="#+id/webview"
android:layout_width="640dp"
android:layout_height="296dp"
android:layout_gravity="bottom"
android:layout_marginTop="8dp" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="640dp"
android:layout_height="67dp"
android:orientation="horizontal">
<TextView
android:id="#+id/textView3"
android:layout_width="200dp"
android:layout_height="63dp"
android:layout_weight="0"
android:gravity="center"
android:text="TextView"
android:textAlignment="center"
android:textSize="30sp" />
<TextView
android:id="#+id/textView2"
android:layout_width="150dp"
android:layout_height="63dp"
android:layout_weight="1"
android:gravity="center"
android:text="TextView"
android:textAlignment="center"
android:textSize="30sp" />
</LinearLayout>
</FrameLayout>
package com.siemens.google_glass_ict21_app.activity;
import android.os.Bundle;
import android.util.Log;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.tabs.TabLayout;
import com.siemens.google_glass_ict21_app.R;
import com.siemens.google_glass_ict21_app.ui.BaseActivity;
import com.siemens.glass.ui.GlassGestureDetector;
import com.siemens.google_glass_ict21_app.wirefragments.BaseWireFragment;
import com.siemens.google_glass_ict21_app.wirefragments.GrommetFragment;
import com.siemens.google_glass_ict21_app.wirefragments.LocateConnectorFragment;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
public class TemporaryPlaceHolderCardsActivity extends BaseActivity {
private List<BaseWireFragment> wireCards = new ArrayList<>();
private ViewPager viewPager;
final ScreenSlidePagerAdapter screenSlidePagerAdapter = new ScreenSlidePagerAdapter(
getSupportFragmentManager());
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_pager_layout);
viewPager = findViewById(R.id.viewPager);
viewPager.setAdapter(screenSlidePagerAdapter);
wireCards.add(GrommetFragment.newInstance("Grommet:", "xyz", "<a href='https://svgshare.com/s/YLZ' ><img src='https://svgshare.com/i/YLZ.svg' title='' /></a>"));
//wireCards.add(LocateConnectorFragment.newInstance("Grommet:", "<a href='https://svgshare.com/s/Z8d' ><img src='https://svgshare.com/i/Z8d.svg' title='' /></a>", "<a href='https://svgshare.com/s/Z8d' ><img src='https://svgshare.com/i/Z8d.svg' title='' /></a>"));
screenSlidePagerAdapter.notifyDataSetChanged();
final TabLayout tabLayout = findViewById(R.id.page_indicator);
tabLayout.setupWithViewPager(viewPager, true);
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return wireCards.get(position);
}
#Override
public int getCount() {
return wireCards.size();
}
}
#Override
public boolean onGesture(GlassGestureDetector.Gesture gesture) {
switch (gesture) {
case TAP:
return true;
case TWO_FINGER_SWIPE_DOWN:
finish();
case SWIPE_DOWN:
return true;
default:
return super.onGesture(gesture);
}
}
}

Android: Recyclerview inside fragment fetching data from TMDbApi gives error: E/RecyclerView: No adapter attached; skipping layout

I've been struggling with a problem on android. I have an app with a drawer which shows fragments depending on what menu item you click in the drawer.
Here's how my app currently works:
This is the drawer with the menu buttons:
Whenever I click a button, for instance Profile, it will load the correct Fragment:
Now I have this problem with the Recyclerview withing my fragmentview of TV Show
When I click on tv shows I get a white empty layout like this:
And this is what I get in the logcat:
com.example.derwishe.movielist E/RecyclerView: No adapter attached; skipping layout
Here's my code:
Fragment Class:
package com.example.derwishe.movielist;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
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 android.widget.Toast;
import com.example.derwishe.movielist.Api.OnGetTvShowsCallback;
import com.example.derwishe.movielist.Api.TvShow;
import com.example.derwishe.movielist.Api.TvShowsRepository;
import java.util.List;
public class TvShowFragment extends Fragment {
private TvShowsRepository tvShowsRepository;
private RecyclerView tvShowList;
private ListAdapter adapter;
Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view =
inflater.inflate(R.layout.fragment_tvshow,container,false);
tvShowsRepository = TvShowsRepository.getInstance();
tvShowList = (RecyclerView)view.findViewById(R.id.showsRecyclerView);
RecyclerView.LayoutManager layoutManager = new
LinearLayoutManager(getActivity());
tvShowList.setLayoutManager(layoutManager);
this.context = context;
tvShowsRepository.getTvShows(new OnGetTvShowsCallback() {
#Override
public void onSuccess(List<TvShow> tvShows) {
adapter = new ListAdapter(tvShows);
tvShowList.setAdapter(adapter);
}
#Override
public void onError() {
Toast.makeText(context, "Please check your internet
connection.", Toast.LENGTH_SHORT).show(); }
});
return view;
}
}
Listadapter class:
package com.example.derwishe.movielist;
import android.support.annotation.NonNull;
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 com.example.derwishe.movielist.Api.TvShow;
import java.util.List;
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.TvShowHolder> {
private List<TvShow> tvShows;
public ListAdapter(List<TvShow> tvShows){
this.tvShows = tvShows;
}
#NonNull
#Override
public TvShowHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.shows_item,parent,false);
return new TvShowHolder(view);
}
#Override
public void onBindViewHolder(TvShowHolder holder, int i) {
holder.bind(tvShows.get(i));
}
#Override
public int getItemCount() {
return tvShows.size();
}
class TvShowHolder extends RecyclerView.ViewHolder{
TextView showTitle;
public TvShowHolder(View itemView){
super(itemView);
showTitle = itemView.findViewById(R.id.showTitle);
}
public void bind(TvShow tvShow){
showTitle.setText(tvShow.getTitle());
}
}
}
MainActivity class with drawer:
package com.example.derwishe.movielist;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
//Reference naar navigatieview voor click events
NavigationView navigationView =findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,drawer,toolbar,R.string.navigation_draw_open,R.string.navigation_draw_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
//initiele fragment openen bij start
if(savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new MovieFragment()).commit();
navigationView.setCheckedItem(R.id.nav_movies);
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.nav_movies:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new MovieFragment()).commit();
break;
case R.id.nav_tvshows:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new TvShowFragment()).commit();
break;
case R.id.nav_watchlist:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new WatchlistFragment()).commit();
break;
case R.id.nav_profile:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).commit();
break;
case R.id.nav_support:
Toast.makeText(this,"Support message activated",Toast.LENGTH_SHORT).show();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if(drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
}else{
super.onBackPressed();
}
}
}
And finally the layout files:
Activity_main.xml
<android.support.v4.widget.DrawerLayout 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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
app:menu="#menu/draw_menu" />
</android.support.v4.widget.DrawerLayout>
fragment_tvshow.xml which holds the recyclerview
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
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"
android:id="#+id/showsRecyclerView"/>
</RelativeLayout>
And shows_item.xml which represents 1 item in the recyclerviewlist
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="0dp"
android:layout_height="50dp"
android:scaleType="fitCenter"
android:layout_margin="8dp"
android:layout_weight="1"
android:id="#+id/showImage"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/showTitle"
android:text="Show Title"
android:textSize="22sp"
android:layout_weight="3"
android:layout_margin="22dp"/>
</LinearLayout>
I think it's because once your fragment's onCreate is first run, the recyclerView isn't assigned an adapter, it's until after you fetch your data (the tv shows) that you set the adapter to your recyclerView.
One way to fix this would be to have a constructor that doesn't take any arguments for your adapter, and a method inside it that would pass in whatever data the recyclerView will need to display. You'd end up with something like this:
public class ListAdapter {
public ListAdapter() {}
public void submitList(final List<TvShow> tvShows) {
this.tvShows = tvShows;
notifyDataChanged();
}
}

firebaseRecyclerAdapter gets filled, yet wont show anything in a dialog - Android Studio

So, I tried putting a recyclerView in a "popup" dialog using a firebaseRecyclerAdapter.
My problem is, that I know for sure the adapter gets filled because I was using the Logcat to tell me when it adds another "user" to the adapter, but it wont show anything in the recyclerview in the dialog.
I'm having this problem for a couple of days and couldn't find an answer yet, glad if you could help me :)
I'm using a main screen which changes fragments, and from a certain fragment I'm calling this specific dialog.
These are my files:
UserViewHolder - the class which holds the "sets" for the cardview:
public static class UserViewHolder extends RecyclerView.ViewHolder
{
View mView;
public UserViewHolder(View itemView)
{
super(itemView);
mView=itemView;
}
public void setName(String name)
{
TextView teacherName=(TextView) mView.findViewById(R.id.txtNameTea);
teacherName.setText(name);
}
public void setEmail(String email)
{
TextView txtEmailTea=(TextView) mView.findViewById(R.id.txtEmailTea);
txtEmailTea.setText(email);
}
public void setImage(final Context ctx, Uri imageUri, User cUser)
{
final ImageView imgProfileTea=(ImageView) mView.findViewById(R.id.imgProfileTea);
Picasso.with(ctx).load(cUser.getImageUri()).into(imgProfileTea);
if(imgProfileTea.getDrawable()==null) {
StorageReference load = FirebaseStorage.getInstance().getReference().child("usersProfilePic/" + cUser.getImageName());
load.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Picasso.with(ctx).load(uri.toString()).into(imgProfileTea);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ctx, e.getMessage(), Toast.LENGTH_LONG);
}
});
}
}
}
Schedules - the fragment which calls the dialog from its toolbar:
package com.example.android.aln4;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
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.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.github.sundeepk.compactcalendarview.CompactCalendarView;
import com.github.sundeepk.compactcalendarview.domain.Event;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import static com.example.android.aln4.LoginActivity.myUser;
import static com.example.android.aln4.dataBase.mDatabaseReference;
import static com.example.android.aln4.dataBase.mFirebaseDatabase;
import static com.example.android.aln4.dataBase.mStorageRef;
import static com.example.android.aln4.navDrawerMain.firebaseRecyclerAdapter;
import static java.lang.System.in;
import static com.example.android.aln4.navDrawerMain.studentsQuery;
public class Schedules extends Fragment {
private Toolbar ScheduleToolbar;
private Button addEvent;
//private TextView txt;
private RecyclerView mRecyclerViewStudentEvent;
private CompactCalendarView compactCalendar;
private SimpleDateFormat dateFormatMonth = new SimpleDateFormat("MMMM-yyyy", Locale.getDefault());
private String[] monthName = {"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"};
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addEvent:
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(getContext());
View mView = getLayoutInflater().inflate(R.layout.dialog_event_creation, null);
mRecyclerViewStudentEvent = (RecyclerView) mView.findViewById(R.id.mRecyclerViewStudentEvent);
mRecyclerViewStudentEvent.setHasFixedSize(true);
mRecyclerViewStudentEvent.setLayoutManager(new LinearLayoutManager(getContext()));
setStudentsList();
mView = getLayoutInflater().inflate(R.layout.dialog_event_creation, null);
final EditText edtEventTitle = (EditText) mView.findViewById(R.id.edtEventTitle);
final TextView txtEventStartTime = (TextView) mView.findViewById(R.id.txtEventStartTime);
final TextView txtEventEndTime = (TextView) mView.findViewById(R.id.txtEventEndTime);
final EditText edtEventLocation = (EditText) mView.findViewById(R.id.edtEventLocation);
Button btnOfferEvent = (Button) mView.findViewById(R.id.btnOfferEvent);
mBuilder.setView(mView);
final AlertDialog dialog = mBuilder.create();
btnOfferEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar startTime = Calendar.getInstance();
Calendar endTime = Calendar.getInstance();
int startHour = Integer.parseInt(txtEventStartTime.getText().toString().substring(0, 2));
int startMinute = Integer.parseInt(txtEventStartTime.getText().toString().substring(3, 5));
startTime.set(Calendar.HOUR_OF_DAY, startHour);
startTime.set(Calendar.MINUTE, startMinute);
int endHour = Integer.parseInt(txtEventEndTime.getText().toString().substring(0, 2));
int endMinute = Integer.parseInt(txtEventEndTime.getText().toString().substring(3, 5));
endTime.set(Calendar.HOUR_OF_DAY, endHour);
endTime.set(Calendar.MINUTE, endMinute);
String mId =/*dataSelected+*/ String.valueOf(startHour) + String.valueOf(startMinute);//+selectedUserID
EventCreation newEvent = new EventCreation(mId, startTime, endTime, edtEventTitle.getText().toString(), edtEventLocation.getText().toString(), R.color.colorPrimary);
dialog.dismiss();
}
});
dialog.show();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
ScheduleToolbar = (Toolbar) getView().findViewById(R.id.schedule_toolbar);
// Setting toolbar as the ActionBar with setSupportActionBar() call
((AppCompatActivity) getActivity()).setSupportActionBar(ScheduleToolbar);
mFirebaseDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mFirebaseDatabase.getReference("users");
mStorageRef = FirebaseStorage.getInstance().getReference();
Calendar cal = Calendar.getInstance();
String month = monthName[cal.get(Calendar.MONTH)];
int year = cal.get(Calendar.YEAR);
getActivity().setTitle(month + "-" + year);
compactCalendar = (CompactCalendarView) getView().findViewById(R.id.compactcalendar_view);
compactCalendar.setUseThreeLetterAbbreviation(true);
long millis = System.currentTimeMillis() % 1000;
Event ev1 = new Event(Color.RED, millis, "First try");
compactCalendar.addEvent(ev1);
compactCalendar.setListener(new CompactCalendarView.CompactCalendarViewListener() {
#Override
public void onDayClick(Date dateClicked) {
//put events into scroll view adapter
}
#Override
public void onMonthScroll(Date firstDayOfNewMonth) {
getActivity().setTitle(dateFormatMonth.format(firstDayOfNewMonth));
}
});
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.schedules, container, false);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
}
private void setStudentsList() {
studentsQuery=mDatabaseReference.orderByChild("teacherNum").equalTo(myUser.getTeacherNum());
firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<User, navDrawerMain.UserViewHolder>(
User.class,R.layout.card_view_teacher,navDrawerMain.UserViewHolder.class,studentsQuery) {
#Override
protected void populateViewHolder(navDrawerMain.UserViewHolder viewHolder, User model, int position) {
viewHolder.setName(model.getFirstName() + " " + model.getLastName());
viewHolder.setEmail(model.getEmail());
viewHolder.setImage(getContext(), Uri.parse(model.getImageUri()), model);
}
};
mRecyclerViewStudentEvent.setAdapter(firebaseRecyclerAdapter);
}
}
The dialog xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="50dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_marginTop="20dp"
android:src="#mipmap/title"/>
<EditText
android:id="#+id/edtEventTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="כותרת"
android:layout_marginRight="50dp"/>
<android.support.v7.widget.RecyclerView
android:layout_marginTop="50dp"
android:id="#+id/mRecyclerViewStudentEvent"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginTop="20dp"
android:orientation="vertical">
<ImageView
android:layout_width="50dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_marginTop="20dp"
android:src="#mipmap/clock"/>
<TextView
android:layout_width="wrap_content"
android:layout_marginRight="50dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="שעת התחלה"
android:textSize="20dp" />
<TextView
android:id="#+id/txtEventStartTime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="5dp"
android:layout_marginRight="50dp"
android:layout_marginTop="5dp"
android:text="21:00" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="25dp"
android:layout_marginRight="50dp"
android:background="#color/darkgray" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="50dp"
android:layout_alignParentRight="true"
android:layout_marginTop="26dp"
android:text="שעת סיום"
android:textSize="20dp" />
<TextView
android:id="#+id/txtEventEndTime"
android:layout_width="match_parent"
android:layout_marginRight="50dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="5dp"
android:layout_marginTop="30dp"
android:text="21:45" />
</RelativeLayout>
<RelativeLayout
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="50dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_marginTop="20dp"
android:src="#mipmap/location"/>
<EditText
android:id="#+id/edtEventLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="מיקום תחילת השיעור"
android:layout_marginRight="50dp"/>
</RelativeLayout>
<Button
android:id="#+id/btnOfferEvent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:layout_gravity="center_horizontal"
android:text="הצע שיעור"/>
</LinearLayout>
One more thing is that I know is that I'm already able to bring up users into the recyclerView in other fragments.. Here's the code in another fragment:
package com.example.android.aln4;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
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 android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import static com.example.android.aln4.dataBase.mDatabaseReference;
import static com.example.android.aln4.dataBase.mFirebaseDatabase;
import static com.example.android.aln4.dataBase.mStorageRef;
import static com.example.android.aln4.navDrawerMain.firebaseRecyclerAdapter;
import static com.example.android.aln4.navDrawerMain.teachersQuery;
public class TeachersList extends Fragment {
private RecyclerView mRecyclerViewTeacher;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("מורים");
mFirebaseDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mFirebaseDatabase.getReference("users");
mStorageRef = FirebaseStorage.getInstance().getReference();
mRecyclerViewTeacher=(RecyclerView) getView().findViewById(R.id.mRecyclerViewTeacher);
mRecyclerViewTeacher.setHasFixedSize(true);
mRecyclerViewTeacher.setLayoutManager(new LinearLayoutManager(getContext()));
setTeachersList();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.teachers_list_frag,container,false);
}
private void setTeachersList() {
teachersQuery=mDatabaseReference.orderByChild("type").equalTo("Teacher");
firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<User, navDrawerMain.UserViewHolder>(
User.class,R.layout.card_view_teacher,navDrawerMain.UserViewHolder.class,teachersQuery) {
#Override
protected void populateViewHolder(navDrawerMain.UserViewHolder viewHolder, User model, int position) {
viewHolder.setName(model.getFirstName()+" "+model.getLastName());
viewHolder.setEmail(model.getEmail());
viewHolder.setImage(getContext(), Uri.parse(model.getImageUri()),model);
}
};
mRecyclerViewTeacher.setAdapter(firebaseRecyclerAdapter);
}
}
and its xml file:
<?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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/mRecyclerViewTeacher"
android:layout_marginTop="57dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
It's one of my first questions here so I apologize if I missed something :)
Any help would be appriciated.
Solved. All I did was regenerating the SHA1 in the firebase settings, and removing the setHasFixedSize line from Schedules activity and it worked just fine.

fragment stuck - can't go to previous fragment

I have a fragment(A) , where another fragment(B) is being opened . When I press back button it just refreshes the fragment(B) instead of exiting from it and returning to fragment A.
I tried poping back the fragment A in the Activity's onBackPressed callback method but it didn't change a thing :
#Override
public void onBackPressed() {
if(B.active)
{
mFragmentManager.popBackStack( A.TAG , 0);
B.active = false;
}
}
** the active boolean is just something I added as part of the solution. It's initialized to TRUE once the fragment is instantiated.
I don't know how to commit a project!
package com.example.a;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
/**
* Created by 77930 on 2015/11/9.
*/
public class ActivityA extends AppCompatActivity{
#InjectView(R.id.c)
LinearLayout c;
#InjectView(R.id.btn)
TextView btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.c);
ButterKnife.inject(ActivityA.this);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.e, FragA.newInstance(), "A");
// fragmentTransaction.addToBackStack("A");
fragmentTransaction.commitAllowingStateLoss();
}
});
}
}
package com.example.a;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
/**
* Created by 77930 on 2015/11/10.
*/
public class FragA extends Fragment{
private View rootView;
public static FragA newInstance() {
return new FragA();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public FragA() {
}
#InjectView(R.id.a)
LinearLayout a;
#InjectView(R.id.btn)
TextView btn;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fraga,container,false);
ButterKnife.inject(this,rootView);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.e, FragB.newInstance(), "B");
fragmentTransaction.addToBackStack("B");
fragmentTransaction.commitAllowingStateLoss();
}
});
return rootView;
}
}
package com.example.a;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
/**
* Created by 77930 on 2015/11/10.
*/
public class FragB extends Fragment{
private View rootView;
public static FragB newInstance() {
return new FragB();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public FragB() {
}
#InjectView(R.id.b)
LinearLayout b;
#InjectView(R.id.btn)
TextView btn;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragb,container,false);
ButterKnife.inject(this, rootView);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().popBackStackImmediate();
}
});
return rootView;
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:id="#+id/c"
android:background="#4b14b1"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/e"
android:layout_width="match_parent"
android:layout_height="300dp">
</FrameLayout>
<TextView
android:id="#+id/btn"
android:textColor="#ffffff"
android:textSize="100dp"
android:gravity="center"
android:text="c"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:id="#+id/a"
android:background="#4b14b1"
android:layout_height="match_parent">
<TextView
android:id="#+id/btn"
android:textColor="#ffffff"
android:textSize="100dp"
android:gravity="center"
android:text="A"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:id="#+id/b"
android:background="#4b14b1"
android:layout_height="match_parent">
<TextView
android:id="#+id/btn"
android:textColor="#ffffff"
android:textSize="100dp"
android:gravity="center"
android:text="B"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>

Categories

Resources