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

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>

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

Android Java - have button change tab

I recently started coding and have been following tutorials. I'm trying to learn how to use a tab activity right now and followed a tutorial to do it by swiping pages. Here's what I've come up with
public class MainActivity extends FragmentActivity {
ViewPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn1 = (Button) findViewById(R.id.btn1);
Button btn2 = (Button) findViewById(R.id.btn2);
pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
}
public void onClickBtn1(View v) {
//when clicked, take to Main2Activity.java
}
public void onClickBtn2(View v) {
//when clicked, take to Main3Activity.java
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return Main2Activity.newInstance("FirstFragment, Instance 1");
case 1: return Main3Activity.newInstance("SecondFragment, Instance 1");
case 2: return Main4Activity.newInstance("ThirdFragment, Instance 1");
default: return Main4Activity.newInstance("ThirdFragment, Default");
}
}
#Override
public int getCount() {
return 3;
}
}
}
Can someone please explain to me what's going on in the MyPageAdapter class please?
Also, is it possible that instead of swiping pages that I use a button? For instance, onClickBtn1 will take me to Main2Activity and onClickBtn2 will take me to Main3Activity. I'd like to continue using the tabs instead of creating a new intent.
Thanks in advance!
Your MyPageAdapter will have as many childs as of your tabs.
For example if you select 1st tab ie position will be 0.
Now in below code new instance of fragment is created for pos 0(First Fragment).
public Fragment getItem(int pos) {
switch(pos) {
case 0: return Main2Activity.newInstance("FirstFragment, Instance 1");
case 1: return Main3Activity.newInstance("SecondFragment, Instance 1");
case 2: return Main4Activity.newInstance("ThirdFragment, Instance 1");
default: return Main4Activity.newInstance("ThirdFragment, Default");
}
}
Switching the tabs on button click is not a cool idea as per user experience.You are using view pager which will help swiping the tabs easily.Execute the code & you will get to know more about the functionality of the code.
if you want to use tabs, you could use 4 fragments in an activity and manage them with ViewPager, by this you can go from one to another by clicking on the tabs and swipe left and right
private void initPager() {
ViewPager pager = (ViewPager) findViewById(R.id.pager);
mAdapter = new MyPagerAdapter(getSupportFragmentManager());
mAdapter.addFragment(firstFragment.newInstance(), getString(R.string.first_fragment_Title));
mAdapter.addFragment(secondFragment.newInstance(), getString(R.string.second_fragment_title));
pager.setAdapter(mAdapter);
TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
tabs.setupWithViewPager(pager);
TextView firstFragmentTabTitle = (TextView) getLayoutInflater().inflate(R.layout.tab_indicator, null);
firstFragmentTabTitle.setText(mAdapter.getPageTitle(0).toString());
TextView secondFragmentTabTitle = (TextView) getLayoutInflater().inflate(R.layout.tab_indicator, null);
secondFragmentTabTitle.setText(mAdapter.getPageTitle(1).toString());
tabs.getTabAt(0).setCustomView(firstFragmentTabTitle);
tabs.getTabAt(1).setCustomView(secondFragmentTabTitle);
pager.setCurrentItem(mAdapter.getCount());
}
and the main activity XML add view pager and tab layout like this :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".fragments.BankCounterFragment">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layoutDirection="ltr"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:contentInsetEnd="16dp"
app:popupTheme="#style/AppTheme.PopupOverlay">
<TextView
android:id="#+id/toolbar_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start|center_vertical"
android:gravity="center|start"
android:text="#string/app_name"
android:textAppearance="#style/TextAppearance.AppCompat.Title"/>
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:layoutDirection="ltr"
app:tabGravity="fill"
app:tabIndicatorColor="#android:color/white"
app:tabIndicatorHeight="3dp"
app:tabMode="fixed"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>

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

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

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!

How to get instance of view's parent fragment:

I have a fragment with an XML layout file. in it I have an 2 clickable ImageViews.
for each ImageView I set an onClick method for example: android:onClick="commentFragmentRemoveOnClick".
In the FragmentActivity (The Activity no the Fragment) I defined it this way:
public void commentFragmentRemoveOnClick(View v)
{
}
No this Fragment is of type CommentFragment and it has a public void getFragmentTag()method
to get it's tag that I save in earlier time. I need to get an instance of the fragment in which the image was clicked to get it's tag.
I tried:
((CommentFragment)v).getParentFragment().getFragmentTag();
and:
((CommentFragment)v).getParent().getFragmentTag();
but eclipse gives me error on both of them, how is this done properly?
To make it more clear this is my CommentFragment:
public class CommentFragment extends Fragment {
private final static String TAG = CommentFragment.class.getSimpleName();
private String fragmentTag;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.comment_fragment_layout,
container, false);
Bundle bundle = getArguments();
String text = bundle.getString("comment");
String fullUser = bundle.getString("user");
String user = fullUser.substring(0, fullUser.indexOf("#"));
String at = bundle.getString("at");
TextView tvCmment = (TextView) rootView.findViewById(R.id.tvComment);
TextView tvUser = (TextView) rootView.findViewById(R.id.tvUser);
TextView tvAt = (TextView) rootView.findViewById(R.id.tvDate);
tvCmment.setText(text);
tvUser.setText(user);
tvAt.setText(at);
return rootView;
}
public void setText(String item)
{
TextView view = (TextView) getView().findViewById(R.id.tvComment);
view.setText(item);
}
public void setFragmentTag(String tag)
{
this.fragmentTag = tag;
}
public String getFragmentTag()
{
return this.fragmentTag;
}
}
and the layout file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/llCommentContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#drawable/try2">
<TextView
android:id="#+id/tvUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tvComment"
android:layout_alignParentTop="true"
android:background="#color/my_gray"
android:text="demo"
android:textStyle="bold"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:textColor="#color/my_even_darker_gray" />
<TextView
android:id="#+id/tvComment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/tvDate"
android:padding="5dp"
android:text="This task is described in more details if you click on it."
android:textColor="#color/my_even_darker_gray" />
<TextView
android:id="#+id/tvAt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:paddingRight="5dp"
android:textColor="#color/my_even_darker_gray"
android:layout_toRightOf="#+id/tvUser"
android:background="#color/my_gray"
android:text="at" />
<TextView
android:id="#+id/tvDate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/tvAt"
android:layout_alignBottom="#+id/tvAt"
android:layout_toRightOf="#+id/tvAt"
android:background="#color/my_gray"
android:text="12/02"
android:textColor="#color/my_even_darker_gray" />
<ImageView
android:id="#+id/iEdit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/tvComment"
android:layout_marginRight="4dp"
android:clickable="true"
android:contentDescription="#drawable/add_comment_button"
android:onClick="commentFragmentEditOnClick"
android:src="#drawable/add_comment_button" />
<ImageView
android:id="#+id/iRemove"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/iEdit"
android:layout_toRightOf="#+id/iEdit"
android:layout_marginRight="4dp"
android:clickable="true"
android:contentDescription="#drawable/add_comment_button"
android:onClick="commentFragmentRemoveOnClick"
android:src="#drawable/add_comment_button" />
</RelativeLayout>
I would love for a little assistance.
Thanks.
I have a general advice for you that would solve your problem and help you in the future -
don't use android:onClick in the xml file, use setOnClickListener in the code itself - need to avoid mixing your views with other parts of the app as much as possible.
Try to keep the Fragment independent of its activity.
If the image is part of the fragment, why does the listener is part of the FragmentActivity?
Use setOnClickListener in the fragment itself, and you might be able to use this Framgent in other pats of the app without being depended on the Activity.
It would also solve your problem of identifying the fragment in which the image was clicked.
v is not an instance of Fragment, that's why Eclipse does not like your code. If you want the instance of a fragment you have to use the FragmentManager and one of its findFragmentByXXX methods.
To get the instance of the fragment that the ImageView was clicked in I did the following:
in the Fragment I set two onClickListeners for both of the images like this:
iEdit = (ImageView)rootView.findViewById(R.id.iEdit);
iEdit.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Log.d(TAG, "pressed edit button");
((PicturesAndCommentsActivity) getActivity()).commentFragmentEditOnClick(fragmentTag);
}
});
iRemove = (ImageView)rootView.findViewById(R.id.iRemove);
iRemove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Log.d(TAG, "pressed remove button");
((PicturesAndCommentsActivity) getActivity()).commentFragmentRemoveOnClick(fragmentTag);
}
});
and in the fragment activity I defined those two methods like this:
public void commentFragmentRemoveOnClick (String tag)
{
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.remove(fragmentManager.findFragmentByTag(tag)).commit();
}
for removing the fragment, and Now I'm working on editing the fragment.

Categories

Resources