I have a sign up fragment whose root layout is ScrollView and the child is LinearLayout. I have edit texts inside that LinearLayout. But when I click on an EditText and try to scroll the view, it doesn't work.
To open this fragment I have to click on signup view at login fragment.
Here is my SignUpFragment.java
public class SignUpFragment extends Fragment {
private EditText etFirstName, etLastName, etEmail, etPassword, etcity, etMobile;
private String firstName, lastName, email, password, city, mobile;
private Button proceed;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_sign_up, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
findViews(view);
proceed.setOnClickListener(v -> {
getStrings();
if (checkFields()) {
Bundle bundle = new Bundle();
bundle.putString("firstName", firstName);
bundle.putString("lastName", lastName);
bundle.putString("email", email);
bundle.putString("password", password);
bundle.putString("mobile", mobile);
bundle.putString("city", city);
jumpToDeliverAddress(bundle);
}
});
}
private void jumpToDeliverAddress(Bundle bundle) {
Fragment fragment = new DeliveryAddressFragment();
FragmentManager fragmentManager = getFragmentManager();
fragment.setArguments(bundle);
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
private boolean checkFields() {
if (firstName.trim().isEmpty()) {
etFirstName.setError("Please enter a valid first name");
return false;
}
if (lastName.trim().isEmpty()) {
etLastName.setError("Please enter a valid last name");
return false;
}
if (email.trim().isEmpty() || (!isEmailValid())) {
etEmail.setError("Please enter a valid email");
return false;
}
if (password.trim().length() < 6) {
etPassword.setError("Password must contain 6 digits");
return false;
}
if (mobile.trim().length() != 10) {
etMobile.setError("Please enter a valid mobile number");
return false;
}
if (city.trim().isEmpty()) {
etcity.setError("Please enter a valid city");
return false;
}
return true;
}
private boolean isEmailValid() {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
private void getStrings() {
firstName = Constants.getString(etFirstName);
lastName = Constants.getString(etLastName);
email = Constants.getString(etEmail);
password = Constants.getString(etPassword);
city = Constants.getString(etcity);
mobile = Constants.getString(etMobile);
}
private void findViews(View view) {
etFirstName = view.findViewById(R.id.firstName);
etLastName = view.findViewById(R.id.lastName);
etEmail = view.findViewById(R.id.email);
etPassword = view.findViewById(R.id.password_edittext);
etcity = view.findViewById(R.id.city);
etMobile = view.findViewById(R.id.mobile_number_edittext);
proceed = view.findViewById(R.id.proceed);
}
}
And the fragment_sign_up.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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:padding="5dp"
tools:context=".fragments.SignUpFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputEditText
android:id="#+id/firstName"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="First name"
android:inputType="textPersonName" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputEditText
android:id="#+id/lastName"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="Last name"
android:inputType="textPersonName" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputEditText
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="Email"
android:inputType="textEmailAddress" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputEditText
android:id="#+id/password_edittext"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="Password"
android:inputType="textPassword"
android:maxLength="10" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputEditText
android:id="#+id/mobile_number_edittext"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="Mobile number"
android:inputType="number"
android:maxLength="10" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputEditText
android:id="#+id/city"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="#string/city" />
</android.support.design.widget.TextInputLayout>
<Button
android:id="#+id/proceed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:text="Proceed to add delivery address" />
</LinearLayout>
</ScrollView>
Please note that, currently, my flow is this:-
Mainactivity loads LoginFragment -> click on signup -> signUpfragment opens.
If I directly open signup fragment from MainActivity, scroll works fine.
MainActivity.java
public class MainActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener, DrawerLocker {
public static SharedPreferences sharedPreferences;
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private ActionBarDrawerToggle toggle;
private Toolbar toolbar;
private VolleyCallback volleyCallback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
initDrawer();
if (checkToken())
jumpToHome();
else
jumpToLogin();
}
private void jumpToLogin() {
Fragment loginFragment = new LoginFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, loginFragment);
fragmentTransaction.commit();
}
private void jumpToHome() {
Fragment homeFragment = new HomeFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, homeFragment);
fragmentTransaction.commit();
}
private boolean checkToken() {
APICall apiCall = new APICall(volleyCallback, this);
String token = apiCall.getTokenFromLocal(this);
return !token.isEmpty();
}
private void initDrawer() {
toggle = new ActionBarDrawerToggle(this,
drawerLayout,
toolbar,
R.string.drawer_open,
R.string.drawer_close);
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
drawerLayout.openDrawer(GravityCompat.START);
}
});
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
drawerLayout = findViewById(R.id.drawer_layout);
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_manage_address)
jumpToManageAddress();
else if (id == R.id.nav_book_order)
jumpToBookOrder();
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
private void jumpToBookOrder() {
Fragment bookOrderFragment = new BookOrderFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, bookOrderFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
private void jumpToManageAddress() {
Fragment manageAddressFragment = new NewAddressFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, manageAddressFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
#Override
public void setDrawerLocked(boolean enabled) {
// if (enabled) {
// drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
//// getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//// WindowManager.LayoutParams.FLAG_FULLSCREEN);
// toggle.setDrawerIndicatorEnabled(false);
// } else {
// drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
//// getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
// toggle.setDrawerIndicatorEnabled(true);
// }
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff">
<LinearLayout
android:id="#+id/container_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:elevation="5dp"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:theme="#style/MyToolbarStyle"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="#+id/container_body"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1">
</FrameLayout>
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:menu="#menu/nav_items">
<RelativeLayout
android:id="#+id/expandable_Frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
LoginFragment.java
public class LoginFragment extends Fragment {
private Button loginButton;
private VolleyCallback volleyCallback;
private EditText mobileNumber, password;
private TextView signup;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
// ((MainActivity) getActivity()).setDrawerLocked(true);
return inflater.inflate(R.layout.fragment_login, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mobileNumber = view.findViewById(R.id.mobile_number_edittext);
loginButton = view.findViewById(R.id.login);
password = view.findViewById(R.id.password_edittext);
signup = view.findViewById(R.id.signup);
// ((MainActivity) getActivity()).getSupportActionBar().setTitle("Login");
signup.setOnClickListener(v -> jumpToSignup());
loginButton.setOnClickListener(v -> {
if (checkLength(mobileNumber, 10) && checkLength(password, 6)) {
apiCallForLogin(Constants.getString(mobileNumber), Constants.getString(password));
} else {
if (!checkLength(mobileNumber, 10))
mobileNumber.setError("Enter a valid mobile number");
else
password.setError("Password should contain atleast 6 digits");
}
});
}
private void jumpToSignup() {
Fragment fragment = new SignUpFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
// fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
private void apiCallForLogin(String mobileNumber, String password) {
APICall apiCall = new APICall(volleyCallback, getContext());
apiCall.addParams("mobile", mobileNumber);
apiCall.addParams("password", password);
}
}
fragment_login.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragments.LoginFragment">
<android.support.design.widget.TextInputLayout
android:id="#+id/mobile_number_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#id/password_layout"
android:layout_centerHorizontal="true">
<android.support.design.widget.TextInputEditText
android:id="#+id/mobile_number_edittext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/enter_your_mobile_number"
android:inputType="number"
android:maxLength="10"
android:minEms="10" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/password_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerInParent="true">
<android.support.design.widget.TextInputEditText
android:id="#+id/password_edittext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Enter Password"
android:inputType="textPassword"
android:maxLength="10"
android:minEms="10" />
</android.support.design.widget.TextInputLayout>
<Button
android:id="#+id/login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/password_layout"
android:layout_centerHorizontal="true"
android:text="Login" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="52dp"
android:text="#string/new_user_signup_here"
android:textColor="#color/black"
android:textSize="15sp"
android:id="#+id/signup"
/>
</RelativeLayout>
Its hard to understand the exact problem that you are having without seeing your MainActivity code. However, based on some common problems, I would suggest to use a NestedScrollView here in this case.
However, you might consider wrapping the ScrollView with an extra LinearLayout. So the final layout will be looking something like the following.
<LinearLayout>
<ScrollView>
<LinearLayout>
<!-- Other views -->
<LinearLayout/>
<ScrollView/>
<LinearLayout/>
Related
how to open and close fragment while clicking on same button . Just like amazon filter button.
when we click first time fragment should apper and then we click on that button again fragment should disapper.
business activity java file
public class business extends AppCompatActivity {
TextView t1, t2;
Button hello;
boolean flag = false;
FragmentTransaction fragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business);
hello = findViewById(R.id.hello);
t1=findViewById(R.id.text1);
t2=findViewById(R.id.textt2);
}
#Override
protected void onStart() {
super.onStart();
hello.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager manager = getSupportFragmentManager();
BusinessSort businessSort = new BusinessSort();
fragmentTransaction = manager.beginTransaction();
if (flag) {
fragmentTransaction.remove(businessSort);
flag=false;
} else {
fragmentTransaction.add(R.id.frgmCont, businessSort);
flag=true;
}
fragmentTransaction.commit();
}
});
}
public void f1(String s1, String s2) {
t1.setText(s1);
t2.setText(s2);
}
}
activity_business.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".business"
android:orientation="vertical"
android:id="#+id/businessLinearLayout">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="hello"
android:id="#+id/hello"
/>
<TextView
android:id="#+id/text1"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="edit1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="edit2"
android:id="#+id/textt2"/>
<FrameLayout
android:id="#+id/frgmCont"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
Fagment file BusinessSort.java
public class BusinessSort extends Fragment {
EditText editText1,editText2;
Button submit;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view =inflater.inflate(R.layout.fragment_business_sort, container, false);
editText1=view.findViewById(R.id.edit1);
editText2=view.findViewById(R.id.edit2);
submit=view.findViewById(R.id.businessfragment_submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s1 = editText1.getText().toString();
String s2 = editText2.getText().toString();
business business = (com.example.project.business) getActivity();
business.f1(s1,s2);
}
});
return view;
}
fragment_business_sort.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".BusinessSort"
android:orientation="vertical">
<EditText
android:id="#+id/edit1"
android:layout_width="match_parent"
android:layout_height="50dp"/>
<EditText
android:id="#+id/edit2"
android:layout_width="match_parent"
android:layout_height="50dp"/>
<Button
android:id="#+id/businessfragment_submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SUBMIT"/>
</LinearLayout>
Try replacing the fragment.
fragmentTransaction.replace(R.id.frgmCont, businessSort);
flag = true;
I hope the code is mostly similar to my approach so let me know if the problem still persists so that I will look into it deeper.
public static boolean fragmentState = false;
onClick(){
if(fragmentState){
fragmentState = false;
getActivity().getFragmentManager().beginTransaction().
remove(SomeFragment.this).commit();
}
else{
fragmentState = true;
Fragment someFragment = new SomeFragment();
FragmentTransaction transaction =
getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, someFragment );
transaction.addToBackStack(null);
transaction.commit();
}
}
Please make sure that your button is not a part of that fragment.
You need to save the state of the fragment.
I have been attempting to call a method from my home activity which should fire once a button is clicked on my settings fragment. The result of this button click should call the greenTorso() and swap an image on my avatar fragment. I am currently getting a null pointer error, please see the logcat attached. I'm not even sure if this is the right way to go about this, but been stuck for a couple of days now and hoped someone could help. Thanks in advance.
My home activity:
public class Home extends AppCompatActivity implements SettingsFragment.Communicator {
private TextView name, email;
Button LogoutButton;
UserSessionManager sessionManager;
Button button;
ImageView Torso;
public void communicateWith(){
AvatarFragment avatarFragment = (AvatarFragment)getSupportFragmentManager().findFragmentById(R.id.nav_avatar);
avatarFragment.greenTorso();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
getWindow().setBackgroundDrawableResource(R.drawable.background2); // sets background to background2.png
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); // hides keyboard on boot
sessionManager = new UserSessionManager(getApplicationContext());
TextView lblName = (TextView) findViewById(R.id.lblName);
TextView lblEmail = (TextView) findViewById(R.id.lblEmail);
BottomNavigationView bottomNav = findViewById(R.id.bottom_nav);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
if(sessionManager.checkLogin())
finish();
// get user data from session
HashMap<String, String> user = sessionManager.getUserDetails();
// get name
String name = user.get(UserSessionManager.KEY_NAME);
// get email
String email = user.get(UserSessionManager.KEY_EMAIL);
//lblName.setText(Html.fromHtml("Name: <b>" + name + "</b>"));
lblEmail.setText(Html.fromHtml("Welcome: <b>" + email + "</b>"));
LogoutButton=(Button)findViewById(R.id.LogoutButton);
Toast.makeText(getApplicationContext(),
"User Login Status: " + sessionManager.isUserLoggedIn(),
Toast.LENGTH_LONG).show();
LogoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Clear the User session data
// and redirect user to LoginActivity
sessionManager.logoutUser();
}
});
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selectedFragment = null;
switch (menuItem.getItemId()) {
case R.id.nav_steps:
selectedFragment = new HomeFragment();
break;
case R.id.nav_avatar:
selectedFragment = new AvatarFragment();
break;
case R.id.nav_settings:
selectedFragment = new SettingsFragment();
break;
}
getSupportFragmentManager()
.beginTransaction().replace(R.id.fragment_container,selectedFragment).commit();
return true;
}
};
}
My settings fragment:
public class SettingsFragment extends Fragment {
public Button button;
public ImageView Torso;
public ImageView ShopGreenTorso;
private Communicator interfaceImplementor;
public interface Communicator
{
public void communicateWith();
}
#Override
public void onAttach(Activity context) {
super.onAttach(context);
this.interfaceImplementor = (Communicator)context;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_settings, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Button button = (Button) getActivity().findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// ImageView torso = (ImageView) getActivity().findViewById(R.id.Torso);
interfaceImplementor.communicateWith();
}
});
}
}
My avatar fragment:
public class AvatarFragment extends Fragment {
public ImageView IV;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_avatar, container, false);
return rootView;
}
public void greenTorso()
{
ImageView IV =(ImageView) getActivity().findViewById(R.id.Torso);
IV.setBackgroundResource(R.drawable.torso2green);
}
}
Avatar layout:
<?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"
xmlns:src="http://schemas.android.com/apk/res-auto"
android:background="#android:color/holo_orange_dark"
>
<ImageView
android:layout_width="500dp"
android:layout_height="530dp"
android:layout_centerInParent="true"
android:orientation="vertical"
android:layout_marginStart="30dp"
android:layout_marginEnd="30dp"
android:id="#+id/Torso"
android:src="#drawable/torso2" >
</ImageView>
</RelativeLayout>
Settings layout:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#D3D3D3"
android:weightSum="10"
tools:context=".Home">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_marginTop="100dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Shop"
android:textSize="26sp"
android:textStyle="bold"
android:gravity="center"
android:layout_marginBottom="10dp"/>
<androidx.cardview.widget.CardView
android:id="#+id/cardview1"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_below="#+id/cardview"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginLeft="16dp"
android:layout_marginTop="10dp"
android:layout_marginRight="16dp"
app:cardBackgroundColor="#color/white"
app:cardCornerRadius="15dp"
app:cardElevation="10dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center_horizontal"
android:paddingLeft="10dp"
android:text="Green Torso"
android:textColor="#color/cardview_dark_background"
android:textSize="20sp"
android:textStyle="bold" />
<ImageView
android:id="#+id/ShopGreenTorso"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="#drawable/torso2green" />
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_gravity="bottom"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:background="#drawable/register_button"
android:shadowColor="#color/colorPrimary"
android:text="10,000S Buy"
android:textColor="#color/white">
</Button>
</androidx.cardview.widget.CardView>
My navigation:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/nav_steps"
android:icon="#drawable/ic_directions_walk_black_24dp"
android:title="Steps" />
<item
android:id="#+id/nav_avatar"
android:icon="#drawable/ic_face_black_24dp"
android:title="Avatar" />
<item
android:id="#+id/nav_settings"
android:icon="#drawable/ic_build_black_24dp"
android:title="Settings" />
</menu>
I have a problem with fragments. I add fragments dynamically without removing old fragments so they can be recalled when I return. But when I applied the following snippet I found that some of the views that came from the activity did not disappear, such as the Button, TextView, and so on. The results I get are overlapping views
MainActivity.Java
public class MainActivity extends AppCompatActivity implements BlankFragment.OnFragmentInteractionListener {
private static final String TAG = "MainActivity";
private Unbinder unbinder;
private FragmentManager fragmentManager;
#BindView(R.id.dynamic_fragment_frame)
FrameLayout frameLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reading);
unbinder = ButterKnife.bind(this);
fragmentManager = this.getSupportFragmentManager();
}
public void openFragment(View view) {
BlankFragment fragment = BlankFragment.newInstance("Test 1");
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_right);
transaction.addToBackStack(null);
transaction.add(R.id.dynamic_fragment_frame, fragment, "BLACK_FRAGMENT");
transaction.commit();
}
#Override
protected void onDestroy() {
unbinder.unbind();
super.onDestroy();
}
#Override
public void onFragmentInteraction(String text) {
Log.d(TAG, "onFragmentInteraction: " + text);
onBackPressed();
}
}
activity_reading.xml
<RelativeLayout
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:background="#00d9ff"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/dynamic_fragment_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<TextView
android:id="#+id/title_read_news"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ini Judul"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:layout_gravity="center"
android:paddingBottom="5dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="openFragment"
android:text="Open"
android:stateListAnimator="#null"/>
</RelativeLayout>
BlankFragment.java
public class BlankFragment extends Fragment {
private static final String ARG_TEXT = "TEXT";
private Unbinder unbinder;
private String mParam1;
private OnFragmentInteractionListener mListener;
#BindView(R.id.tv_blank_fragment)
TextView tvTitle;
#BindView(R.id.back_btn)
Button backBtn;
#BindView(R.id.next_btn)
Button nextBtn;
private FragmentManager fragmentManager;
public BlankFragment() {
// Required empty public constructor
}
public static BlankFragment newInstance(String param1) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putString(ARG_TEXT, param1);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_TEXT);
}
fragmentManager = getFragmentManager();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_blank, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
unbinder = ButterKnife.bind(this, view);
tvTitle.setText(mParam1);
backBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String test = "test dari fragment";
sendBack(test);
}
});
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
public void sendBack(String sendback) {
if (mListener != null) {
mListener.onFragmentInteraction(sendback);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(String text);
}
}
fragment_blank.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#cfcf1d"
tools:context=".BlankFragment">
<TextView
android:id="#+id/tv_blank_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
<Button
android:id="#+id/next_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/back_btn"
android:layout_alignParentStart="true"
android:text="Create new Fragment" />
<Button
android:id="#+id/back_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:text="back" />
</RelativeLayout>
Everything went smoothly but the result of my Mainactivity layout still appeared on fragment. Please help me
Result as shows as below:
here 1
here 2
In activity_reading, the fragment container view (dynamic_fragment_frame) is declared first, so the button and the text view will be displayed on top of it. If you move the fragment container to the bottom, the fragments will be displayed correctly, so the layout should look something like this:
<RelativeLayout
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:background="#00d9ff"
tools:context=".MainActivity">
<TextView
android:id="#+id/title_read_news"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ini Judul"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:layout_gravity="center"
android:paddingBottom="5dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="openFragment"
android:text="Open"
android:stateListAnimator="#null"/>
<FrameLayout
android:id="#+id/dynamic_fragment_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
<RelativeLayout
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:background="#00d9ff"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/dynamic_fragment_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<TextView
android:id="#+id/title_read_news"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ini Judul"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:layout_gravity="center"
android:paddingBottom="5dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="openFragment"
android:text="Open"
android:stateListAnimator="#null"/>
</RelativeLayout>
With the above layout, Imagine that the TextView and Button are over the FragmeLayout. So when you add a Fragment to the FrameLayout, the TextView and Button are still over the FragmeLayout. To hide these views, you should use TextView.setVisibility(View.GONE) and Button.setVisibility(View.GONE) when adding a Fragment
I know this issue has been put out there 100 times, but nothing I've seen solves this. I have a button in a layout called fragment_main which is shown to another layout: activity_main. That button opens a fragment called AddEditFragment, which allows users to add info to a form that then spits it into a recyclerview(fragment_main) that is shown in MainActivity.
I have both layouts due to having a navigation drawer in a linearlayout in activity_main and the recyclerview and button in fragment_main constraintlayout. However I have onDelete/Edit/Save methods already up and going in MainActivity, so it only makes sense to me to put the button onClickListener there as well. Except since the button isn't in the main layout, activity_main, I get a fatal null object exception.
Even though fragment_main is shown in activity_main is there a way around this so the OnClick method can be put into MainActivity for a button in a linked layout?
MainActivity.java
public class MainActivity extends AppCompatActivity implements RecyclerViewAdapter.OnVehicleClickListener,
FragmentAddEdit.OnSaveClicked,
NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
// Launcher view
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FragmentMainActivity()).commit();
navigationView.setCheckedItem(R.id.nav_garage);
}
Button button_add = findViewById(R.id.button_add);
button_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AddEditRequest(null);
}
});
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_garage:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FragmentMainActivity()).commit();
break;
case R.id.nav_history:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FragmentHistory()).commit();
break;
case R.id.nav_upcoming:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FragmentUpcoming()).commit();
break;
case R.id.nav_about:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FragmentAbout()).commit();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onSaveClicked() {
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment AddEditFragment = fragmentManager.findFragmentById(R.id.fragment_container);
if (AddEditFragment != null) {
getSupportFragmentManager().beginTransaction()
.remove(AddEditFragment)
.commit();
}
}
public void onEditClick(#NonNull Vehicle vehicle) {
AddEditRequest(vehicle);
}
#Override
public void onDeleteClick(#NonNull Vehicle vehicle) {
}
private void AddEditRequest(Vehicle vehicle) {
Intent detailIntent = new Intent(this, FragmentAddEdit.class);
if (vehicle != null) {
detailIntent.putExtra(Vehicle.class.getSimpleName(), vehicle);
startActivity(detailIntent);
}
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".com.carupkeep.MainActivity"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
app:menu="#menu/drawer_menu" />
</android.support.v4.widget.DrawerLayout>
fragment_main.xml
<?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:id="#+id/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".com.carupkeep.FragmentMainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:id="#+id/no_vehicles"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="#string/no_vehicle_message"
android:textSize="22sp"
android:textStyle="normal|bold"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintTop_creator="1"/>
<Button
android:id="#+id/button_add"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:drawableLeft="#drawable/ic_add"
android:drawablePadding="10dp"
android:drawableTint="#color/colorAdd"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="#string/addVehicle"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/vehicle_list" />
<android.support.v7.widget.RecyclerView
android:id="#+id/vehicle_list"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/no_vehicles"
app:layout_constraintVertical_bias="0.0" />
</android.support.constraint.ConstraintLayout>
UPDATE
I got close but still feel so far. I've given up on trying to keep it in MainActivity and put it in FragmentMainAcitivity as suggested. Except now I have 2 can't resolve errors. The first being on view in view.findViewById button initialization AND on fragment_container in the callback method. Any thoughts on how to resolve this?
public class FragmentMainActivity extends Fragment {
Button button_add = view.findViewById(R.id.button_add);
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
button_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fragmentManager = getFragmentManager();
Fragment AddEditFragment = fragmentManager.findFragmentById(R.id.fragment_container);
getFragmentManager().beginTransaction().replace(fragment_container, AddEditFragment).commit();
}
});
}
}
easier way to do it is to put
onClick="AddEditRequestView"
in your fragment_main.xml
so it will be
<Button
android:id="#+id/button_add"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:drawableLeft="#drawable/ic_add"
android:drawablePadding="10dp"
android:drawableTint="#color/colorAdd"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="#string/addVehicle"
android:onClick="AddEditRequestView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/vehicle_list" />
and in your MainActivity.java
add this method
public void AddEditRequestView(View viewc){
AddEditRequest(null);
}
and delete these code from your activity
Button button_add = findViewById(R.id.button_add);
button_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AddEditRequest(null);
}
});
I have a simple main java "GameMode" that will show 3 tabs fragments, one of them is "HkmjSetting" (will be shown below), now when I run the app, it works just fine, but any click on the button has no response. No red lines were found in android studio..
GameMode java:
public class GameMode extends AppCompatActivity {
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_mode);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_game_mode, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (getArguments().getInt(ARG_SECTION_NUMBER)==1) {
View rootView = inflater.inflate(R.layout.fragment_hkmj_setting, container, false);
return rootView;
} else if (getArguments().getInt(ARG_SECTION_NUMBER)==2) {
View rootView = inflater.inflate(R.layout.fragment_quickmj_setting, container, false);
return rootView;
} else {
View rootView = inflater.inflate(R.layout.fragment_hkmj_setting, container, false);
// TextView textView = (TextView) rootView.findViewById(R.id.section_label);
//textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
}
HkmjSetting java:
public class HkmjSetting extends Fragment {
Button btn_next;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_hkmj_setting, container, false);
btn_next = (Button) view.findViewById(R.id.btn_next);
btn_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* Intent intent = new Intent(v.getContext(), MainActivity.class);
startActivity(intent);*/
Toast.makeText(getActivity(), "TESTING", Toast.LENGTH_SHORT).show();
}
});
return view;
}
}
Run results no error, but nothing happen when clicked on the "btn_next", this may be a silly question to many of you, but please help...Thanks!
2018-05-08 Updating Xml layout codes as comments suggest, I simplified a bit for easier reading
fragment_hkmj_setting.xml :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".GameSetting">
<!-- TODO: Update blank fragment layout -->
<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=".HkmjSetting">
<LinearLayout
android:id="#+id/edtxList_6to10"
android:layout_width="57dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.72"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.602">
<TextView
android:id="#+id/tv_10Fan"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginBottom="0dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="#string/tv_10Fan"
android:textColor="#color/ColorDropiii"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.024"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.982" />
</LinearLayout>
<ImageButton
android:id="#+id/ibtn_setting2"
android:layout_width="58dp"
android:layout_height="52dp"
android:layout_marginBottom="8dp"
android:layout_marginStart="4dp"
android:layout_marginTop="8dp"
android:contentDescription="#string/tv_Setting"
android:src="#drawable/hkmj"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="#+id/tv_pageTitle"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
</LinearLayout>
<Button
android:id="#+id/btn_next"
android:layout_width="139dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:background="#color/ColorDropii"
android:text="#string/btn_next"
android:textColor="#color/ColorDropiv"
android:textSize="24sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.501"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.876" />
</android.support.constraint.ConstraintLayout>
</FrameLayout>
activity_game_mode.xml :
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".GameMode">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
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:layout_weight="1"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay"
app:title="#string/app_name">
</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.support.design.widget.TabItem
android:id="#+id/tabItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="香港麻雀" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="跑馬仔" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="台灣麻雀" />
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
Change the getItem() method body to if (position == 2) { return new HkmjSetting(); } else { return PlaceholderFragment.newInstance(position + 1); }
as suggested by #Mike M.
Thanks! it works!