Android DK Trying to show/hide part of the UI via Fragments - java

So I am very new to the Android DK, and was sailing pretty fine until I started trying to mess with Fragments.
At the core of it, what I'm trying to do is have a series of buttons on my app's screen, and whichever button the user presses will change what text/spinners/buttons display on the screen.
How I decided to implement that was via Fragments. I can't figure out why my Fragment isn't displaying however, this should be a relatively simple example.
I had a activity_main.xml that is relatively simple. I've changed variable names, but see below:
<LinearLayout android:id="#+id/mainActivity"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:animateLayoutChanges="true" >
<Button
android:id="#+id/buttonD"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/d_name"
android:onClick="dMenuButton" />
<RelativeLayout
android:id="#+id/fragment_container"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<Button
android:id="#+id/buttonR"
android:layout_below="#id/fragment_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/r_name"
android:onClick="rButton" />
</LinearLayout>
And the corresponding MainActivity.java
public void dMenuButton(View view){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.show(dFragment);
fragmentTransaction.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// remove title
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
dFragment = new DFragment();
fragmentTransaction.add(R.id.fragment_container, dFragment);
fragmentTransaction.commit();
}
}
And the fragment_d.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"
android:orientation="vertical" >
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="20dp"
android:text="#string/text1"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Spinner
android:id="#+id/numD"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#id/text1"
android:layout_toRightOf="#id/text1" />
</RelativeLayout>
With its respective DFragment.java
public class DFragment extends Fragment {
static Spinner dSpinner;
ArrayAdapter<CharSequence> dAdapter;
RelativeLayout view;
public static DFragment newInstance() {
DFragment dFragment = new DFragment();
return dFragment ;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = (RelativeLayout) inflater.inflate(R.layout.fragment_d,
container, false);
createSpinners();
return view;
}
private void createSpinners() {
dSpinner = (Spinner) view.findViewById(R.id.numD);
dAdapter= ArrayAdapter.createFromResource(getActivity().getBaseContext(),
R.array.numD,
android.R.layout.simple_spinner_item);
}
}
Currently, the fragment layout is covering up the buttons beneath it. Any help in forcing it to push down the components below would be great.
Thanks in advance.

You are definitely on the right track with the visibility of the fragment_container. You could leave that as visible constantly, then allow the fragment transactions to change what is being displayed in that container.
Depending on your requirements, you could simply perform a .replace(R.layout.fragment_container, anotherFragment) to change which fragment is being displayed (code is pseudo only).
As for the buttons, are you adding them to the activity_main.xml or are they being added in the fragment's layout? As long as you add the new buttons/text after the fragment_container layout in the main activity layout, you should be fine. Let me know exactly what you are trying to achieve with the buttons/text!
Good luck!

Related

Fragment transaction from main activity doesn't work

I'm writing my first android app using fragments but I can't figure out why it doesn't change view from main activity to fragment.
This is my mainActivity.java:
public class MainActivity extends AppCompatActivity {
Button fragment1_BTN, fragment2_BTN;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragment1_BTN = findViewById(R.id.frag1_btn);
fragment2_BTN = findViewById(R.id.frag2_btn);
fragment1_BTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
replaceFragment(new Frag1());
}
});
fragment2_BTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
replaceFragment(new Frag2());
}
});
}
private void replaceFragment(Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.frameLayout, fragment);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.commit();
}}
This is my activity_main.xml:
<?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">
<FrameLayout
android:id="#+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:gravity="center">
<Button
android:id="#+id/therapists_btn"
android:layout_width="150dp"
android:layout_height="60dp"
android:backgroundTint="#color/teal_700"
android:text="button 1"
android:layout_marginRight="10dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/patients_btn" />
<Button
android:id="#+id/patients_btn"
android:layout_width="150dp"
android:layout_height="60dp"
android:layout_marginLeft="10dp"
android:backgroundTint="#color/teal_700"
android:text="button 2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/therapists_btn"
app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>
</FrameLayout> </androidx.constraintlayout.widget.ConstraintLayout>
The problem is that when I click on button 1 I see the view of first fragment and also of main activity.
How can I see only the fragment view?
your frameLayout container for Fragments is placed before LinearLayout, Fragments View is loaded into it and is visible, but also rest of Views is drawn after that (as order in XML) on top of it. just setVisibility(View.GONE) for this LinearLayout when you are loading Fragment (set for it some id and use findViewById as for buttons). another approach would be to put your LinearLayout inside container - you are using replace method so Fragment will remove your buttons, but in that case these are gone forever then and you don't have an easy option for bringing them back (with your current code - only whole Activity restart)
it would be way better (by design) if your Activity wouldn't have these buttons at all, only container, and on start would check if container has anything loaded (e.g. getChildCount()==0), if not then load some initial Fragment for preventing displaying empty Activity

Hiding elements from toolbar, implemented on a single activity, on various fragments

I'm trying to hide certain elements from my custom toolbar which I've deployed in the MainActivity (it is the only activity in my app).
Accordingly, BotomNavigation has been implemented which handles 3 fragments namely Home, Records and Statistics.
The main toolbar.xml is composed as follows:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:elevation="4dp">
<TextView
android:id="#+id/toolbarTitle"
style="#style/TextAppearance.AppCompat.Widget.ActionBar.Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<ImageView
android:id="#+id/profileImage"
android:layout_width="25dp"
android:layout_height="25dp"
android:src="#drawable/ic_account_circle_white_50dp"/>
As you can clearly see, it has
TextView, which dynamically displays and centers the name of the fragment the current user is on and
an ImageView which shows the authenticated user's image wherein the src is just a placeholder if the user doesn't have a profile picture.
Not everything works as expected using the following MainActivity.java :
public class MainActivity extends AppCompatActivity {
private TextView mTitle;
private String mUsername, mEmail;
private Uri mProfileImage;
private ImageView mProfileImageView;
private android.support.v7.widget.Toolbar mToolbar;
private static final String TAG = "BottomNavigation";
private BottomNavigationView.OnNavigationItemSelectedListener navListener;
public BottomNavigation() {
navListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment;
switch (item.getItemId()) {
case R.id.nav_home:
mTitle.setText("Home");
mToolbar.getMenu().findItem(R.id.profileImage).setVisible(false);
fragment = new HomeFragment();
loadFragment(fragment);
break;
case R.id.nav_records:
mTitle.setText("Records");
mToolbar.getMenu().findItem(R.id.profileImage).setVisible(false);
fragment = new RecordsFragment();
loadFragment(fragment);
break;
case R.id.nav_stats:
mTitle.setText("Statistics");
fragment = new StatisticsFragment();
loadFragment(fragment);
Glide.with(getApplicationContext()).load(mProfileImage).into(mProfileImageView);
break;
}
return true;
}
};
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bottom_naviation);
//replacing the default actionbar with custom toolbar
mToolbar = findViewById(R.id.tool_bar);
setSupportActionBar(mToolbar);
mTitle = mToolbar.findViewById(R.id.toolbarTitle);
//disabling the output of the appname on the toolbar
getSupportActionBar().setDisplayShowTitleEnabled(false);
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
//load the Home fragment by default
loadFragment(new HomeFragment());
mTitle.setText("Home");
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
mProfileImage = currentUser.getPhotoUrl();
mProfileImageView = mToolbar.findViewById(R.id.profileImage);
}
private void loadFragment(Fragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.commit();
}
}
What I'm trying to implement is to hide the ImageView on the Home and Record fragment but Statistics.
To do this, I used the following in the respective case statements:
mToolbar.getMenu().findItem(R.id.profileImage).setVisible(false);
However, for some reason the ImageView remains as is. What's interesting is:
1. that the place holder image continues to remain until and unless I move to Statistics fragment and fetch the image.
2. once fetched, the image remains continue to live in the toolbar even if move out from the Statistics, possibly, it is not getting hidden in the first place.
3. if I rotate into landscape, the fetched image gets erased, and I'm yet again presented with the placeholder.
I've also tried hiding the visibility by setting visibility gone on the ImageView itself, but to no avail.
mProfileImageView.setVisibility(View.GONE);
How can I actually go about in implementing the right logic, should I implement the toolbar in each and every fragment, which is certainly not a healthy practice and defeats the purpose of modular fragments?
Following are some screenshots in order for a better understanding:
ImageView not getting hidden, shows placeholder
Is visible even in the Records fragment
placeholder replaced with the user's image (fetched using FirebaseUI Auth)
rotating into landscape switches back to Home fragment and placeholder is replaced with the fetched image
as soon as I switch into statistics, imageview is replaced with the intended image
Views inside toolbar is same like other views I tried changing visibility it works.
toolbar.findViewById(R.id.image).setVisibility(View.VISIBLE);
public class TestActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.findViewById(R.id.image).setVisibility(View.GONE);
toolbar.postDelayed(new Runnable() {
#Override
public void run() {
toolbar.findViewById(R.id.image).setVisibility(View.VISIBLE);
}
}, 5000);
}
}
my toolbar xml
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/holo_blue_light"
android:contentInsetEnd="0dp"
android:contentInsetLeft="0dp"
android:contentInsetRight="0dp"
android:contentInsetStart="0dp"
app:contentInsetEnd="0dp"
app:contentInsetLeft="0dp"
app:contentInsetRight="0dp"
app:contentInsetStart="0dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginRight="10dp"
android:src="#drawable/ic_launcher_foreground" />
<TextView
android:id="#+id/appTitle"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:gravity="center"
android:text="Title"
android:textColor="#android:color/background_dark"
android:textSize="20sp" />
</RelativeLayout>
</android.support.v7.widget.Toolbar>

Dynamically creating two fragments that differentiate between the two in same activities

So I've searched for hours trying to find an answer to this specific problem I'm having with no luck. Would be great if someone can help me out.
So essentially I have a MainActivity.java, FragmentA.java, activity_main.xml, and fragment.xml. So what fragment.xml has is just a container that have 3 buttons in a box that when pressed Start showing a number starting from 3 as the buttons text. So when you click the button again, it changes the button text to 2 and then 1 and then 0 and then back to 3. All the logic that decrements the numbers and changes the button text to that number is in the FragmentA.java class. All that's logic is working, I've tested it. Finally I create and add FragmentA dynamically to MainActivity's activity_main.xml LinearLayout when an add button in actionbar is clicked.
So now when you press the add button in the actionbar in MainActivity, the fragment.xml view is correctly appended to activity_main.xml's LinearLayout. The problem is, only the first fragment that's appended in the LinearLayout is working (numbers decrement) when button is clicked. The other fragment copies are not working or doing anything, but just showing. So the buttons decrement logic is only working for the first added view. Why is that? I thought the point of fragments was to elimanate duplication. I'm guessing this is some ID issue with the same fragment being created multiple times? Any idea on how to fix this?
FragmentA.java
Button b1, b2, b3;
int[] mCounter = {3, 3, 3};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment, null);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
b1 = (Button) getActivity().findViewById(R.id.button);
b1.setOnClickListener(this);
b2 = (Button) getActivity().findViewById(R.id.button2);
b2.setOnClickListener(this);
b3 = (Button) getActivity().findViewById(R.id.button3);
b3.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.button:
b1.setText(Integer.toString(mCounter[0]));
decrementCounterByButtonPosition(0);
break;
case R.id.button2:
b2.setText(Integer.toString(mCounter[1]));
decrementCounterByButtonPosition(1);
break;
case R.id.button3:
b3.setText(Integer.toString(mCounter[2]));
decrementCounterByButtonPosition(2);
break;
}
}
public void decrementCounterByButtonPosition(int counterId) {
if (mCounter[counterId] != 0) {
mCounter[counterId]--;
} else {
mCounter[counterId] = 3;
}
}
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_add_exercise) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FragmentA ContainerFragment = new FragmentA();
fragmentTransaction.add(R.id.container, ContainerFragment, "HELLO");
fragmentTransaction.commit();
return true;
}
return super.onOptionsItemSelected(item);
}
activity_main.xml
<ScrollView
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="#1FDA9A">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity"
android:orientation="vertical"
android:id="#+id/container">
</LinearLayout>
fragment.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="wrap_content"
android:paddingTop="0dp"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity" >
<LinearLayout
android:id="#+id/globalContainer"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="80dp"
android:background="#fff"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:backgroundTint="#333"
android:gravity="center_vertical|center_horizontal">
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:maxWidth="10dp"
android:maxHeight="10dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button2"
android:maxWidth="10dp"
android:maxHeight="10dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button3"
android:maxWidth="10dp"
android:maxHeight="10dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp" />
</LinearLayout>
</LinearLayout>
Any help appreciated. Thanks :D
In addition to Abdullah Asendar's answer, you have another thing to fix.
The problem is with the way you are getting your views.
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
b1 = (Button) getActivity().findViewById(R.id.button);
b1.setOnClickListener(this);
b2 = (Button) getActivity().findViewById(R.id.button2);
b2.setOnClickListener(this);
b3 = (Button) getActivity().findViewById(R.id.button3);
b3.setOnClickListener(this);
}
This finds views from the Activity, not from your fragment.
The correct way to do this is:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment, container, false);
b1 = (Button) v.findViewById(R.id.button);
b1.setOnClickListener(this);
b2 = (Button) v.findViewById(R.id.button2);
b2.setOnClickListener(this);
b3 = (Button) v.findViewById(R.id.button3);
b3.setOnClickListener(this);
return v;
}
and get rid of your onActivityCreated override because it no longer does anything special.
notice the subtle change View v = inflater.inflate(R.layout.fragment, container, false);
I am not quite sure but I think the problem is in the ContainerFragment Object
FragmentA ContainerFragment = new Fragment();
try to change it to :
FragmentA ContainerFragment = new FragmentA();
if you can't pass the object fragmentTransaction.add
do this:
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
I hope this helps.

viewPager not displaying fragment

for this project, I have tabs that have to display something under them and i'm using view pager but for some reason, the fragment layout isn't showing up on screen. I get a blank screen but there is no error or anything. I have been googling and searching for hours now and even started a new project just to make sure it was not a build error but still no luck in finding a solution to my problem.
I have done examples like this many times and used the exact same steps but for some reason, it just isn't working this time. Any help would be greatly appreciated
Here is my mainActivity class
public class MainActivity extends ActionBarActivity {
Toolbar toolbar;
ViewPager myViewPager;
SlidingTabLayout mySlidingTabs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
myViewPager = (ViewPager) findViewById(R.id.viewPager);
myViewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager(), this));
mySlidingTabs = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
mySlidingTabs.setViewPager(myViewPager);
}
}
Here is my custom adapter class
public class MyPagerAdapter extends FragmentPagerAdapter {
private Context context;
private String[] tabNames = {"Beverages", "Deli & Bakery", "Fresh Produce", "Health & Beauty", "Meat & Seafood", "Natural Foods", "Pet Care"};
public MyPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
return new Beverages();
}
else if (position == 1) {
return new DeliBakery();
}
return null;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return tabNames[position];
}
}
Here is my main activty.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar_layout"
android:layout_height="wrap_content"
android:layout_width="match_parent" />
<!-- The Sliding tab -->
<bello.myapplication.SlidingTabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/sliding_tabs"/>
<!-- The pager that allows us to swipe between fragments -->
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white" />
</LinearLayout>
and here is one of my tab's xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tab fragment 1"
android:textSize="50dp"
android:padding="5dp" />
</RelativeLayout>
Here is one of my fragment classes
public class Beverages extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.beverages_tab, container, false);
return view;
}
}
When something strange like this happens, try to use Log.i("title", "message") to track if every class/methods are being called.
In your case, it seens that your viewpager isn't in the screen.
If I understood your code, your <include> tag is including the second xml code you posted right?
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tab fragment 1"
android:textSize="50dp"
android:padding="5dp" />
</RelativeLayout>
It looks like your layout_height="match_parent" is filling all the space on your screen, giving no space to your ViewPager being inflated by the system, try to change it to layout_height="wrap_content and you should be done.
If not, try to change the background of your ViewPager to check if it is on the screen and is not being hided by something else.
Figured out the problem. The viewpager background color and the background color of the tabs where the same so it made it look like there was a black activity. So for anyone else out there with the same problem, try changing either the text color of your tabs.xml or change the background of your viewpager

Reason for a fragment to not show up

so I know there are a few topics around here that ask about this but none seemed to be the cause of my issue. I have an ActionBarActivity that is going to be switching between a few different fragments, but I'm having a problem getting one of the fragments to show up. The activity does show a fragment when it is first loaded and does that fine. Here is the code that is setting up the initial fragment with the method to switch between fragments that I'm using.
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_container);
final ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("");
if (savedInstanceState == null) navigateTo(START_SCREEN);
}
public void navigateTo(int sectionNumber, Serializable objectParam) {
Fragment fragment = null;
switch (sectionNumber) {
case START_SCREEN:
fragment = createStartScreenFragment(); //returns an instance of the class for this fragment
break;
case SCREEN_TWO:
fragment = createSecondScreenFragment(); //returns an instance of the class for this fragment
break;
}
if (fragment == null) return;
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction trans = fm.beginTransaction();
trans.add(R.id.activity_container, fragment, fragment.getTag());
trans.commit();
trans.show(fragment);
}
activity_containers.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:id="#+id/activity_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
The first fragment that loads successfuly
<GridLayout
android:id="#+id/fragment_start_screen"
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.android.Activity">
<TextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
/>
...
</GridLayout>
And here is the fragment xml that isn't showing up
<TextView android:id="#+id/section_label" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:fadingEdge="vertical"
android:cacheColorHint="#00000000"
android:fastScrollEnabled="true"
android:padding="2dp">
</ListView>
And here is the misbehaving fragments relevant code:
public class SecondFragment extends Fragment {
public final static int SECTION_NUMBER = 1;
private String mTag = "TAG";
private ParentActivity parentActivity;
public SecondFragment() {
}
public static fragment newInstance() {
SecondFragment fragment = new SecondFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onAttach(final Activity activity) {
super.onAttach(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
parentActivity = (ParentActivity) getActivity();
View rootView = inflater.inflate(R.layout.fragment_second_fragment, container, false);
ListView list = (ListView) rootView.findViewById(R.id.list);
return super.onCreateView(inflater, container, savedInstanceState);
}
}
The biggest problem I'm having here is that there is no error message shown. The text view in the first fragment is supposed to trigger the second fragment to show up on the screen. This used to work when I had that fragment as a DialogFragment and just called .show() on an instance of it. I need it to be a regular fragment now and it doesn't show up. There's no error message that I can see, though debugging it does show it running through all of my code successfully and it looks like its properly inflating the view.
So what could I be missing here that is preventing the fragment from displaying?
Your layout
<TextView android:id="#+id/section_label" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:fadingEdge="vertical"
android:cacheColorHint="#00000000"
android:fastScrollEnabled="true"
android:padding="2dp">
</ListView>
Should be within a ViewGroup
<?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">
<TextView android:id="#+id/section_label" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:fadingEdge="vertical"
android:cacheColorHint="#00000000"
android:fastScrollEnabled="true"
android:padding="2dp">
</ListView>
</LinearLayout>
And you should return rootView in onCreateView().
Also, you might need to use replace method of Fragment Manager to replace one fragment with another, instead of add.

Categories

Resources