Why is my floating action button not responding to clicks? - android-fragments

I have two floating action buttons in a fragment that is being created by a ViewPager. My intention is for the FABs to do the same thing that can be done in the ViewPager, so that the user can have a choice in terms of navigation. My problem is that the FABs do not respond to clicks initially, so if I click the left FAB, and then click the right FAB, the ViewPager will flip to the left instead of flipping to the right. What am I doing wrong?
Here is my code:
activity_view_pager:
<?xml version="1.0" encoding="utf-8"?>
<androidx.viewpager.widget.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
fragment_test:
<?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">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Title"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/a"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="200dp"
android:text="Description"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/b"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="250dp"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/c"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="300dp"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/left_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="50dp"
android:layout_marginTop="450dp"
android:src="#drawable/ic_left_arrow"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/right_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="450dp"
android:layout_marginEnd="50dp"
android:src="#drawable/ic_right_arrow"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
ViewPagerActivity:
package com.fl4me.android.exampleapplication;
import static com.fl4me.android.exampleapplication.TestAdapter.EXTRA_ID;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;
public class ViewPagerActivity extends AppCompatActivity {
public static int index;
public static ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_pager);
index = (int) getIntent().getSerializableExtra(EXTRA_ID);
viewPager = (ViewPager) findViewById(R.id.view_pager);
FragmentManager fragmentManager = getSupportFragmentManager();
viewPager.setAdapter(new FragmentStatePagerAdapter(fragmentManager) {
#Override
public Fragment getItem(int position) {
return TestFragment.newInstance(position);
}
#Override
public int getCount() {
return 5;
}
});
for(int i = 0; i < Test.testData.length; i++) {
if(i == index) {
viewPager.setCurrentItem(i);
break;
}
}
}
}
TestFragment:
package com.fl4me.android.exampleapplication;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class TestFragment extends Fragment {
private static final String ARG_ID = "Id";
private int Id;
private String a;
private TextView aTV;
private String b;
private TextView bTV;
private int c;
private TextView cTV;
private FloatingActionButton leftBtn;
private FloatingActionButton rightBtn;
public static TestFragment newInstance(int Id) {
Bundle args = new Bundle();
args.putSerializable(ARG_ID, Id);
TestFragment fragment = new TestFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_test, container, false);
Id = getArguments().getInt(ARG_ID);
a = Test.testData[Id].getA();
b = Test.testData[Id].getB();
c = Test.testData[Id].getC();
aTV = (TextView) view.findViewById(R.id.a);
aTV.setText(a);
bTV = (TextView) view.findViewById(R.id.b);
bTV.setText(b);
cTV = (TextView) view.findViewById(R.id.c);
cTV.setText(String.valueOf(c));
leftBtn = view.findViewById(R.id.left_btn);
rightBtn = view.findViewById(R.id.right_btn);
leftBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ViewPagerActivity.viewPager.setCurrentItem(ViewPagerActivity.index--);
}
});
rightBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ViewPagerActivity.viewPager.setCurrentItem(ViewPagerActivity.index++);
}
});
return view;
}
}

This is probably happening because you are post-incrementing or post-decrementing the index instead of pre-incrementing or pre-decrementing it. I think that you should know how post and pre incrementation works, but here is something to read.
Basically the index that you are providing for the setCurrentItem is not evaluated on the spot as index + 1 or index - 1, but it gets its new value only after the execution of the line of code in which there is an expression index++ or index--. This is why you got that "lag" in switching pages that you have described.
So, in your listener for the rightBtn the code should probably be like this:
ViewPagerActivity.viewPager.setCurrentItem(++ViewPagerActivity.index);
The listener for the leftBtn will be analogous, but with --.

Related

Null exeption encountered even though I have coded the button in both xml and java files with same ID

Found the solution I had forgot to include setContentView in my code
This my first app and I am building a login app.This is my Login page and it is connected to my frontpage and main activity through buttons.
I have coded the java and xml page to best of my Knowldge.My reset button'btn_link_to_register' and
'btn_action_back_to_homepage' are throwing null exception. They are both present in my java and xml codes. Usins Intent intent and calling it separately isn't changing anything.Please help!!
'LoginActivity.java'
'''package com.bharath.smartdata;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class LoginActivity extends AppCompatActivity {
private EditText inputEmail, inputPassword;
private FirebaseAuth auth;
private ProgressBar progressBar;
private Button btnSignup, btnSignOut, btnReset ,btn_link_to_register, btn_action_back_to_homepage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnSignup = (Button) findViewById(R.id.btn_signup);
btnSignOut =(Button) findViewById(R.id.btnsignout);
btn_action_back_to_homepage = (Button) findViewById(R.id.btn_action_back_to_homepage);
btnReset = (Button) findViewById(R.id.btn_reset_password);
btn_link_to_register =(Button) findViewById(R.id.btn_link_to_register);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
//Redirect to Homepage
btn_action_back_to_homepage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, Frontpage.class));
finish();
}
});
//Redirect To Signup Page
btn_link_to_register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, SignupActivity.class));
}
});
//Login
btnSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
//authenticate user
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
// there was an error
if (password.length() < 6) {
inputPassword.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
});
btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ResetPassowordActivity.class));
}
});
//SignOut
btnSignOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signOut();
}
});
}
//sign out method
public void signOut() {
auth.signOut();
}
});
}
public void clickFuncTion(View view) {
}
}'''
'activity_login.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"
android:fitsSystemWindows="true"
android:background="#42CDDF"
tools:context="com.bharath.smartdata.LoginActivity">
<!-- Link to Login Screen -->
<TextView
android:id="#+id/textView"
android:layout_width="298dp"
android:layout_height="47dp"
android:text="Welcome Back!!!"
android:textSize="36sp"
app:layout_constraintBottom_toTopOf="#+id/imageView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.495"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.355" />
<ImageView
android:id="#+id/imageView"
android:layout_width="342dp"
android:layout_height="193dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.362"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.171"
app:srcCompat="#drawable/background" />
<EditText
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/email"
android:inputType="textEmailAddress"
android:maxLines="1"
android:singleLine="true"
android:textColor="#android:color/white"
app:layout_constraintBottom_toTopOf="#+id/password"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView"
app:layout_constraintVertical_bias="0.284" />
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="76dp"
android:focusableInTouchMode="true"
android:hint="#string/hint_password"
android:imeActionLabel="#+id/login"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true"
android:textColor="#android:color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/email"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="#+id/email"
app:layout_constraintTop_toBottomOf="#+id/imageView"
app:layout_constraintVertical_bias="0.052" />
<Button
android:id="#+id/btn_signup"
style="?android:textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
android:text="#string/btn_login"
android:textColor="#android:color/black"
android:textStyle="bold"
android:onClick="clickFuncTion"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/password"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="#+id/password"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.635" />
<Button
android:id="#+id/btn_reset_password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#null"
android:text="#string/btn_forgot_password"
android:textAllCaps="false"
android:textColor="#color/colorAccent"
android:onClick="clickFuncTion"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.806" />
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="center|bottom"
android:visibility="gone"
app:layout_constraintBottom_toTopOf="#+id/textView"
app:layout_constraintEnd_toEndOf="parent" />
<Button
android:id="#+id/btn_link_to_register"
android:layout_width="411dp"
android:layout_height="56dp"
android:text="#string/btn_link_to_register"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
android:onClick="clickFuncTion"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.887" />
<Button
android:id="#+id/btn_action_back_to_homepage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/action_back_to_homepage"
android:onClick="clickFuncTion"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.976" />
<Button
android:id="#+id/btnsignout"
android:layout_width="414dp"
android:layout_height="58dp"
android:text="#string/btn_sign_out"
android:onClick="clickFuncTion"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.465"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.72" />
</androidx.constraintlayout.widget.ConstraintLayout>
'''
'Error Message'
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.bharath.smartdata.LoginActivity.onCreate(LoginActivity.java:53)
EDITED VERSION:
You added this line of code for every button:
android:onClick="clickFuncTion"
but in your java file (at the bottom of the file), you didn't add intent to move to another activity (clickFuncTion function was emtpy):
public void clickFuncTion(View view) {
}
If you want to use an onClickListener (like this one):
btn_action_back_to_homepage.setOnClickListener(new View.OnClickListener(){
}
you have to remove these:
android:onClick="clickFuncTion"
public void clickFuncTion(View view) {
}
EXAMPLE:
OPTION 1 (without using onClick property and clickFuntion for the button):
activity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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">
<Button
android:id="#+id/testButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test this button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
MainActivity.java file:
package com.example.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button testButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testButton = (Button) findViewById(R.id.testButton);
testButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("test button", "test button");
}
});
}
}
OPTION 2 (using onClick property and clickFuntion for the button):
activity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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">
<Button
android:id="#+id/testButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test this button"
android:onClick="clickFuncTion"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
MainActivity.java file:
package com.example.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button testButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testButton = (Button) findViewById(R.id.testButton);
}
public void clickFuncTion(View view) {
Log.d("test button", "test button");
}
}
Both produce the same result:
2021-04-19 14:42:50.727 27886-27886/com.example.myapplication D/testĀ button: test button

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

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

Replace one fragment to another fragment in the swipable TabHost

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

Android Fragment not showing up in my application

I have a strange issue with my Fragment, I get no errors at runtime (I'm using Android Studio v8.7 and the Gradle compiles just fine) but when my app runs on my phone it's now showing up, it looks like an empty Activity.
Activity.class
package android.bignerdranch.com.criminalintent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.view.MenuItem;
public class CrimeActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime);
// These are Fragments from the app.v4 package, it's needed to make the app compatible with API < 11
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
if(fragment == null) {
fragment = new Fragment();
fm.beginTransaction().add(R.id.fragmentContainer, fragment).commit();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Fragment.class
package android.bignerdranch.com.criminalintent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
public class CrimeFragment extends Fragment {
private Crime mCrime;
private EditText mTitleField;
private Button mDateButton;
private CheckBox mSolvedCheckbox;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_crime, container, false);
mTitleField = (EditText)v.findViewById(R.id.crime_title);
mTitleField.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mCrime.setTitle(s.toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
mDateButton = (Button)v.findViewById(R.id.crime_date);
mDateButton.setText(mCrime.getDate().toString());
mDateButton.setEnabled(false);
mSolvedCheckbox = (CheckBox)v.findViewById(R.id.crime_solved);
mSolvedCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mCrime.setSolved(isChecked);
}
});
return v;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCrime = new Crime();
}
}
Activity.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Fragment.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/crime_title_label"
style="?android:listSeparatorTextViewStyle" />
<EditText
android:id="#+id/crime_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/crime_title_hint" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/crime_details_label"
style="?android:listSeparatorTextViewStyle" />
<Button
android:id="#+id/crime_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp" />
<CheckBox
android:id="#+id/crime_solved"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:text="#string/crime_solved_label" />
</LinearLayout>
Can somebody point me in the right direction and tell me what could solve my issue?
Ok i found the errors, I was instantiating the wrong Fragment.
Instead of
if(fragment == null) {
fragment = new Fragment();
fm.beginTransaction().add(R.id.fragmentContainer, fragment).commit();
It should be
if(fragment == null) {
fragment = new CrimeFragment();
fm.beginTransaction().add(R.id.fragmentContainer, fragment).commit();

Show/Hide Fragments and change the visibility attribute programmatically

This is a 2 part problem. What I'm having is a 3 Fragment layout where the 3'rd Fragment(FragmentC) is added dynamically when the user taps a button found in another fragment. Then, after it's added the 3'rd Fragment has a button to maximize/minimize it.
UPDATE: Scrool at the end for SOLUTION
PROBLEM 1:
I'm trying to change the visibility attribute of a FrameLayout that acts as a container for the 3'rd fragment(R.id.fragment_C).
What the code is supposed to do is to generate another fragment that, originally has an XML containing android:visibility = "gone". Then, the Fragment is added when tapping a button and the visibility is suppose to change to VISIBLE.
I know this has been covered before, but after 4 hours of trying to make it work I decided to ask what I'm doing wrong.
PROBLEM 2:
After the 3'rd fragment is generated I have a minimize/maximize button that's supposed to hide the first 2 Fragments and allow the 3'rd Fragment to fill the screen.
The problem is the Views of the first 2 Fragments are not removed when using .setVisibility(View.GONE). This has been covered before as well, but I can't figure out why it doesn't work in my code.
The code so far(sorry if it's to verbose but I thought it's better to include all details for you folks):
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:orientation="vertical"
>
<FrameLayout
android:id="#+id/fragment_A"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#CCCCCC"
>
</FrameLayout>
<FrameLayout
android:id="#+id/fragment_B"
android:layout_width="fill_parent"
android:layout_height="300dp"
android:layout_below="#id/fragment_A"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:background="#B4B4B4"
>
</FrameLayout>
<FrameLayout
android:id="#+id/fragment_C"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#id/fragment_B"
android:layout_centerHorizontal="true"
android:layout_marginTop="0dp"
android:background="#A3A3A3"
android:visibility="gone"
>
</FrameLayout>
</RelativeLayout>
land/main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:paddingLeft="0dp"
android:paddingRight="0dp" >
<LinearLayout
android:id="#+id/fragments_container"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:baselineAligned="false" >
<FrameLayout
android:id="#+id/fragment_A"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="0.5"
android:background="#CCCCCC" >
</FrameLayout>
<FrameLayout
android:id="#id/fragment_B"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="0.5"
android:background="#B4B4B4"
>
</FrameLayout>
</LinearLayout>
<FrameLayout
android:id="#+id/fragment_C"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#id/fragment_container"
android:layout_centerHorizontal="true"
android:layout_marginTop="0dp"
android:background="#A3A3A3"
android:visibility="gone" >
</FrameLayout>
</RelativeLayout>
MainActivity.java
package com.example.android.fragments_proto.activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import com.example.android.fragments_proto.R;
import com.example.android.fragments_proto.fragment.GMC_DateSelectionFragment;
import com.example.android.fragments_proto.fragment.GMC_ProdUnitSelectionFragment;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
FragmentManager fm = getSupportFragmentManager();
Fragment fragmentA = fm.findFragmentById(R.id.fragment_A);
Fragment fragmentB = fm.findFragmentById(R.id.fragment_B);
if (fragmentA == null) {
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragment_A, new FragmentA());
ft.commit();
}
if (fragmentB == null) {
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragment_B, new FragmentB());
ft.commit();
}
}
}
Now the XML and .java files for the first Fragment.
fragment_A.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:gravity="center_horizontal"
>
<DatePicker
android:id="#+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
FragmentA.java
package com.example.android.fragments_proto.fragment;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.Toast;
import com.example.android.fragments_proto.R;
public class FragmentA extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_A, container, false);
DatePicker datePicker = (DatePicker) view.findViewById(R.id.datePicker1);
datePicker.setCalendarViewShown(true);
datePicker.setSpinnersShown(false);
datePicker.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Activity activity = getActivity();
if (activity != null) {
Toast.makeText(activity, "You Touched ME!", Toast.LENGTH_SHORT).show();
}
return false;
}
});
return view;
}
}
Now the XML and .java files for the Fragment that contains the button that when tapped adds the content in R.id.fragment_C
fragment_B.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="0.1"
>
<ListView
android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
</ListView>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:orientation="horizontal"
android:gravity="center"
android:layout_height="wrap_content">
<Button
android:id="#+id/button"
android:text="#string/btn_fragment"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
</LinearLayout>
FragmentB.java
package com.example.android.fragments_proto.fragment;
import android.app.Activity;
import android.os.Bundle;
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.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import com.example.android.fragments_proto.R;
public class FragmentB extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragmentB, container, false);
ListView listView = (ListView) view.findViewById(R.id.listView1);
Button button = (Button) view.findViewById(R.id.button);
String[] machines = new String[] { "MachineId-001", "MachineId-002", "MachineId-003", "MachineId-004", "MachineId-005", "MachineId-006", "MachineId-007", "MachineId-008"};
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.select_dialog_multichoice, machines));
final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.fragment_C);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Activity activity = getActivity();
if (activity != null) {
getFragmentManager().beginTransaction().replace(R.id.fragment_C, new FragmentC()).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE).addToBackStack(null).commit();
frameLayout.setVisibility(View.VISIBLE);
}
}
});
return view;
}
}
The XML and .java files for the Fragment that's supposed to be added.
fragment_C.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:orientation="horizontal"
android:gravity="center"
android:layout_height="wrap_content">
<Button
android:id="#+id/maximize_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Maximize Me!" />
</LinearLayout>
<TextView
android:id="#+id/text_view"
android:textIsSelectable="true"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FF33FF"
/>
</LinearLayout>
FragmentC.java
package com.example.android.fragments_proto.fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.example.android.fragments_proto.R;
public class FragmentC extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_C, container, false);
TextView textView = (TextView) view.findViewById(R.id.text_view);
final Fragment fragmentA = getFragmentManager().findFragmentById(R.id.fragment_A);
final Fragment fragmentB = getFragmentManager().findFragmentById(R.id.fragment_B);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
if (fragmentA.isVisible() && fragmentB.isVisible()) {
ft.hide(fragmentA);
ft.hide(fragmentB);
fragmentA.getView().setVisibility(View.GONE);
fragmentB.getView().setVisibility(View.GONE);
button.setText("Minimize Me!");
ft.addToBackStack(null);
} else {
ft.show(fragmentA);
ft.show(fragmentB);
fragmentA.getView().setVisibility(View.VISIBLE);
fragmentB.getView().setVisibility(View.VISIBLE);
button.setText("Maximize Me!");
ft.addToBackStack(null);
}
ft.commit();
}
});
return view;
}
}
Found the problem and a solution thanks to Moesio
PROBLEM:
My error was that I was trying to find a view (in FragmentB.java) with
final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.fragment_C);
This line was returning null so when the code reached the point where it was supposed to do a .setVisibility() then the app. would return a nullPointerException.
The same happened for FragmentC.java (so my 2 problems were related). The Views were not removed because my findViewById was null!
SOLUTION:
Just search for your View with getActivity.findViewById(R.id.your_view);
In FragmentB you're trying get a view which is not on your contentView
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_b, container, false);
// this is in fragment_b layout
ListView listView = (ListView) view.findViewById(R.id.listView1);
Button button = (Button) view.findViewById(R.id.button);
/* ... */
// ****************************************
// this is NOT in fragment_b layout, which causes null
// ****************************************
final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.fragment_C);
/* ... */
}
Try:
final FrameLayout frameLayout = (FrameLayout) getActivity().getWindow().findViewById(R.id.fragment_C);
Whereas R.id.fragment_C is inflated and setted on MainActivity.
Moreover, I had the same problem until use an extra flag
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
final Fragment fragmentC = new FragmentC();
fragmentTransaction.add(R.id.fragment_C, fragmentC);
fragmentTransaction.commit();
menuIsOn = false;
final View fragmentCView = findViewById(R.id.fragment_C);
final Button btn = (Button) findViewById(R.id.btn);
btnPowers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!menuIsOn) {
fragmentCView.setVisibility(View.VISIBLE);
} else {
fragmentCView.setVisibility(View.INVISIBLE);
}
menuIsOn = !menuIsOn;
}
});
Create the Instances of fragments and add instead of replace
FragA fa= new FragA();
FragB fb= new FragB();
FragC fc= new FragB();
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragmnt_container, fa);
fragmentTransaction.add(R.id.fragmnt_container, fb);
fragmentTransaction.add(R.id.fragmnt_container, fc);
fragmentTransaction.show(fa);
fragmentTransaction.hide(fb);
fragmentTransaction.hide(fc);
fragmentTransaction.commit();
suppose we want to to hide and show different fragments based on our action
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.hide(fa);
fragmentTransaction.show(fb);
fragmentTransaction.hide(fc);
fragmentTransaction.commit();

Resources