I'm new to Android Studio and I'm trying the build a TabLayout inside a fragment.
Originally the tab layout was made in an Acitvtie, but I modified the code to make it work in a fragment.
11/23 15:56:40: Launching 'app' on Samsung Galaxy Tab S7 FE API 22.
Install successfully finished in 3 s 16 ms.
$ adb shell am start -n "com.ssl.app/com.ssl.app.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 22349 on device 'Samsung_Galaxy_Tab_S7_FE_API_22 [emulator-5554]'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
E/libprocessgroup: failed to make and chown /acct/uid_10097: Read-only file system
W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
I/art: Late-enabling -Xcheck:jni
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter androidx.vectordrawable.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
D/: HostConnection::get() New Host Connection established 0xb40f16f0, tid 22349
D/Atlas: Validating map...
D/: HostConnection::get() New Host Connection established 0xae85f2e0, tid 22367
I/OpenGLRenderer: Initialized EGL, version 1.4
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/EGL_emulation: eglCreateContext: 0xae834d00: maj 2 min 0 rcv 2
D/EGL_emulation: eglMakeCurrent: 0xae834d00: ver 2 0 (tinfo 0xae839400)
D/OpenGLRenderer: Enabling debug mode 0
D/EGL_emulation: eglMakeCurrent: 0xae834d00: ver 2 0 (tinfo 0xae839400)
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ssl.app, PID: 22349
java.lang.ClassCastException: com.google.android.material.tabs.TabLayout cannot be cast to androidx.viewpager2.widget.ViewPager2
at com.ssl.app.ui.tablayout.TabLayoutFragment.onCreateView(TabLayoutFragment.java:32)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:3104)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:524)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1890)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1814)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1751)
at androidx.fragment.app.FragmentManager$5.run(FragmentManager.java:538)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
TabLayoutFragment.class
package com.ssl.app.ui.tablayout;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;
import com.google.android.material.tabs.TabLayout;
import com.ssl.app.R;
//import com.ssl.app.R;
public class TabLayoutFragment extends Fragment {
TabLayout tabLayout;
ViewPager2 viewPager2;
MyViewPagerAdapter myViewPagerAdapter;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_tablayout,container,false);
tabLayout = (TabLayout) root.findViewById(R.id.tab_layout);
viewPager2 = (ViewPager2) root.findViewById(R.id.tab_layout);
myViewPagerAdapter = new MyViewPagerAdapter(this);
viewPager2.setAdapter(myViewPagerAdapter);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager2.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
tabLayout.getTabAt(position).select();
}
});
return root;
}
}
MyViewPagerAdapter.class
package com.ssl.app.ui.tablayout;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
public class MyViewPagerAdapter extends FragmentStateAdapter {
public MyViewPagerAdapter(#NonNull Fragment fragment) {
super(fragment);
}
#NonNull
#Override
public Fragment createFragment(int position) {
switch (position) {
case 0:
return new FragmentAlpha();
case 1:
return new FragmentBeta();
case 2:
return new FragmentCharlie();
case 3:
return new FragmentDelta();
default:
return new FragmentAlpha();
}
}
#Override
public int getItemCount() {
return 4;
}
}
fragment_tablelayout.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".ui.tablayout.TabLayoutFragment" >
<!-- TabLayout -->
<com.google.android.material.tabs.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tab_layout">
<!-- TABS -->
<com.google.android.material.tabs.TabItem
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Alpha"
tools:ignore="HardcodedText" />
<com.google.android.material.tabs.TabItem
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Beta"/>
<com.google.android.material.tabs.TabItem
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Charlie"/>
<com.google.android.material.tabs.TabItem
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Delta"/>
</com.google.android.material.tabs.TabLayout>
<!-- ViewPager -->
<androidx.viewpager2.widget.ViewPager2
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/view_pager"
android:layout_below="#id/tab_layout"/>
</RelativeLayout>
MainActivity.class
package com.ssl.app;
import android.os.Bundle;
import android.view.Menu;
import com.google.android.material.navigation.NavigationView;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import com.ssl.app.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
private ActivityMainBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.appBarMain.toolbar);
DrawerLayout drawer = binding.drawerLayout;
NavigationView navigationView = binding.navView;
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_Stocklist, R.id.nav_Settings)
.setOpenableLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
}
I probably overlooked something
Related
please help me to find out where is the trouble in my code, i tried to set onclick listener to delete the item from the database, howerver i does nothing, i checked the code again and again but i didn't find out where in the code that cause the problem.
please help me
thanks
The 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="wrap_content"
android:clipChildren="false"
android:clipToPadding="false"
android:padding="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_toLeftOf="#id/btn_delete">
<TextView
android:id="#+id/tv_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Title"
android:textColor="#color/white"
android:textSize="20sp"
android:gravity="center"
android:padding="8dp"
/>
<TextView
android:id="#+id/tv_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Content"
android:textSize="20sp"
android:gravity="start"
android:padding="10dp"
android:textColor="#color/white" />
</LinearLayout>
<Button
android:id="#+id/btn_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="delete"
android:backgroundTint="#color/transparent"
android:textColor="#color/white"
android:layout_alignParentEnd="true"
android:layout_marginEnd="40dp"
android:layout_alignParentRight="true"/>
</RelativeLayout>
the adapter
package com.haki.mysimplehakidiarynotes.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.haki.mysimplehakidiarynotes.InterfaceDeleteListener;
import com.haki.mysimplehakidiarynotes.objects.ItemsObject;
import com.haki.mysimplehakidiarynotes.R;
import java.util.ArrayList;
public class ItemsAdapter extends RecyclerView.Adapter<ItemsAdapter.ItemViewHolder>{
private Context mContext;
private ArrayList<ItemsObject> arrayList;
private InterfaceDeleteListener deleteListener;
public ItemsAdapter(Context mContext, InterfaceDeleteListener deleteListener) {
this.mContext = mContext;
this.deleteListener = deleteListener;
}
public void setData(ArrayList<ItemsObject> arrayList){
this.arrayList = arrayList;
notifyDataSetChanged();
}
#NonNull
#Override
public ItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).
inflate(R.layout.layout_items, parent, false);
return new ItemViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ItemViewHolder holder, int position) {
ItemsObject object =arrayList.get(position);
if (object==null){
return;
}
holder.txtTitle.setText(object.getTitle());
holder.txtContent.setText(object.getContent());
holder.btn_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteListener.onClickDeleteListen(object);
}
});
}
#Override
public int getItemCount() {
if (arrayList!=null){
return arrayList.size();
}
return 0;
}
public class ItemViewHolder extends RecyclerView.ViewHolder {
private TextView txtTitle;
private TextView txtContent;
private Button btn_delete;
public ItemViewHolder(#NonNull View itemView) {
super(itemView);
txtTitle =itemView.findViewById(R.id.tv_title);
txtContent =itemView.findViewById(R.id.tv_content);
btn_delete = itemView.findViewById(R.id.btn_delete);
}
}
}
the main
package com.haki.mysimplehakidiarynotes.fragments.diary_tabs;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.haki.mysimplehakidiarynotes.InterfaceDeleteListener;
import com.haki.mysimplehakidiarynotes.adapters.ItemsAdapter;
import com.haki.mysimplehakidiarynotes.databases.DiaryDatabase;
import com.haki.mysimplehakidiarynotes.objects.ItemsObject;
import com.haki.mysimplehakidiarynotes.R;
import java.util.ArrayList;
public class DiaryLogFragment extends Fragment implements InterfaceDeleteListener {
private RecyclerView recyclerView;
private ArrayList<ItemsObject> arrayList = new ArrayList<>();
private ItemsAdapter adapter;
public DiaryLogFragment() {
}
public static DiaryLogFragment newInstance() {
DiaryLogFragment fragment = new DiaryLogFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_diary_log, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
recyclerView = view.findViewById(R.id.rcv_items);
//arrayList.add(new ItemsObject("thử nghiệm","nội dung thử nghiệm"));
arrayList = (ArrayList<ItemsObject>) DiaryDatabase.getInstance(getActivity()).userDAO().getAllData();
adapter = new ItemsAdapter(getActivity(), this::onClickDeleteListen);
adapter.setData(arrayList);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity()
,LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
}
#Override
public void onResume() {
super.onResume();
arrayList = (ArrayList<ItemsObject>) DiaryDatabase.getInstance(getActivity()).userDAO().getAllData();
adapter.setData(arrayList);
}
#Override
public void onClickDeleteListen(ItemsObject object) {
DiaryDatabase.getInstance(getActivity()).userDAO().delete(object);
arrayList = (ArrayList<ItemsObject>) DiaryDatabase.getInstance(getActivity()).userDAO().getAllData();
adapter.setData(arrayList);
}
}
the interface
package com.haki.mysimplehakidiarynotes;
import com.haki.mysimplehakidiarynotes.objects.ItemsObject;
public interface InterfaceDeleteListener {
void onClickDeleteListen(ItemsObject object);
}
the Dao
package com.haki.mysimplehakidiarynotes.databases;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import com.haki.mysimplehakidiarynotes.objects.ItemsObject;
import java.util.List;
#Dao
public interface DiaryDAO {
//Bước 1. Tạo insert vào cơ sở dữ liệu
#Insert
void insert(ItemsObject itemsObject);
#Query("SELECT * FROM user order by id DESC")
List<ItemsObject> getAllData();
#Delete
void delete(ItemsObject object);
}
i checked the code many times, however i didn't findout where is the cause that doen'st delete the item from the database
Im trying to use a searchview to create a search bar in a simple map application, however i get the next error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.SearchView.setOnQueryTextListener(android.widget.SearchView$OnQueryTextListener)' on a null object reference
This is my code:
MapsActivity:
package com.example.actividad13mapactivity;
import androidx.fragment.app.FragmentActivity;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.widget.SearchView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.example.actividad13mapactivity.databinding.ActivityMapsBinding;
import java.io.IOException;
import java.util.List;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private ActivityMapsBinding binding;
SupportMapFragment mapFragment;
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
searchView = findViewById(R.id.sv_location);
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
String location = searchView.getQuery().toString();
List <Address> adressList = null;
if (location != null || !location.equals("")){
Geocoder geocoder = new Geocoder(MapsActivity.this);
try {
adressList = geocoder.getFromLocationName(location,1);
}catch (IOException e){
e.printStackTrace();
}
Address address = adressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(),address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title(location));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,10));
}
return false;
}
#Override
public boolean onQueryTextChange(String query) {
return false;
}
});
binding = ActivityMapsBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
Layout:
<?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=".MapsActivity">
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<SearchView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/sv_location"
android:queryHint="Search..."
android:iconifiedByDefault="false"
android:layout_margin="100dp"
android:elevation="5dp"
android:background="#drawable/bg_round"/>
</RelativeLayout>
I created a bottom navigation bar with 3 icons and 3 different fragments linked to them.
On clicking an icon,
1.the icon changes
2. icon color changes
3. that related fragment appears on screen
On swipe,
only that fragment is changing.(icon is not changing).
Menu with 3 icons
<item
android:id="#+id/ic_birthdays"
android:title="#string/birthdays"
android:icon="#drawable/change_ic_cake"
/>
<item
android:id="#+id/ic_add"
android:title="#string/add"
android:icon="#drawable/change_ic_add"
/>
<item
android:id="#+id/ic_profile"
android:title="#string/profile"
android:icon="#drawable/change_ic_profile"
/>
The three icons linked in menu are:
1.Birthdays icon
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="#drawable/ic_cake_clicked" />
<item android:state_checked="false" android:drawable="#drawable/ic_cake_not_clicked"/>
</selector>
2.Add Icon
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/ic_add_not_clicked" android:state_checked="false"/>
<item android:drawable="#drawable/ic_add_clicked" android:state_checked="true"/>
</selector>
3.Profile icon
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/ic_profile_not_clicked" android:state_checked="false"/>
<item android:drawable="#drawable/ic_profile_clicked" android:state_checked="true"/>
</selector>
MainActivity.java
package com.example.bottom_nav;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.example.bottom_nav.databinding.ActivityMainBinding;
import com.google.android.material.navigation.NavigationBarView;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.ViewGroup;
public class MainActivity extends AppCompatActivity {
ActivityMainBinding ui;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ui = ActivityMainBinding.inflate(getLayoutInflater());
ViewGroup root = ui.getRoot();
setContentView(root);
//Instantiating 3 fragments
ViewPageAdapter viewPageAdapter = new ViewPageAdapter(this);
ui.viewPager.setAdapter(viewPageAdapter);
//Linking those three fragments to their respective icons of bottom nav bar
ui.bottomNav.setOnItemSelectedListener(
new NavigationBarView.OnItemSelectedListener(){
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.ic_birthdays:
ui.viewPager.setCurrentItem(0);
break;
case R.id.ic_add:
ui.viewPager.setCurrentItem(1);
break;
case R.id.ic_profile:
ui.viewPager.setCurrentItem(2);
break;
}
return true;
}
}
);
}
}
layout_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".MainActivity">
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/bottom_nav" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_nav"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:menu="#menu/bottom_navigation_menu" />
</RelativeLayout>
ViewPageAdapter.java
package com.example.bottom_nav;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import com.example.bottom_nav.fragments.add;
import com.example.bottom_nav.fragments.birthdays;
import com.example.bottom_nav.fragments.profile;
public class ViewPageAdapter extends FragmentStateAdapter {
public ViewPageAdapter(#NonNull FragmentActivity fragmentActivity) {
super(fragmentActivity);
}
#NonNull
#Override
public Fragment createFragment(int position) {
switch (position){
case 1: return new add();
case 2: return new profile();
default: return new birthdays();
}
}
#Override
public int getItemCount() {
return 3;
}
}
The 3 fragments code
1.birthdays.java
package com.example.bottom_nav.fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.bottom_nav.R;
public class birthdays extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_birthdays, container, false);
}
}
2.add.java
package com.example.bottom_nav.fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.bottom_nav.R;
public class add extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_add, container, false);
}
}
3.profile.java
package com.example.bottom_nav.fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.bottom_nav.R;
public class profile extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_add, container, false);
}
}
You need to have a listener on viewpager, and keep track of previous item selected,
so create a global variable,
Global variable:
MenuItem previousMenuItem;
then a viewpager listener:
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (previousMenuItem != null) {
previousMenuItem.setChecked(false);
}
else {
mBottomNavigationView.getMenu().getItem(0).setChecked(false);
}
mBottomNavigationView.getMenu().getItem(position).setChecked(true);
previousMenuItem = mBottomNavigationView.getMenu().getItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
Don't forget to set a default item (first) to be selected of BottomNav on activity start.
I would like to add a button click event to my code for an Android app.
This is my code:
package com.example.myapplication;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.view.MenuItem;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;
public class FirstFragment extends Fragment {
#Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState
) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_first, container, false);
}
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NavHostFragment.findNavController(FirstFragment.this)
.navigate(R.id.action_FirstFragment_to_SecondFragment);
}
});
}
public void button1_Click(View view)
{
EditText editTextNumber = (EditText)findViewById(R.id.editTextNumber);
}
}
It says that findViewById is undefined.
How can I fix this?
Thanks for all of your help. It is working fine.
You can change the text of your textbox with a button click using the setText method:
public void onBtnChangeText(View view) {
EditText editText = (EditText)findViewById(R.id.simpleEditText);
editText.setText("New text");
}
My xml file is:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#0390FF"
android:onClick="onBtnChangeText"
android:text="Click to change text"
android:textAllCaps="false"
android:textSize="20sp" />
<EditText
android:id="#+id/simpleEditText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Old text"
android:gravity="center"/>
The text will be changed from "Old text" to "New text" when click the button:
Just got many problems sorted out on my bottom navigation bar, but now the app crashes whenever I click on any of the 3 navigation bar Icons.
Error
2020-07-23 15:41:26.397 25876-25876/com.example.sociate11 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sociate11, PID: 25876
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
at androidx.fragment.app.FragmentTransaction.doAddOp(FragmentTransaction.java:245)
at androidx.fragment.app.BackStackRecord.doAddOp(BackStackRecord.java:180)
at androidx.fragment.app.FragmentTransaction.replace(FragmentTransaction.java:343)
at androidx.fragment.app.FragmentTransaction.replace(FragmentTransaction.java:293)
at com.example.sociate11.activityHome$2.onNavigationItemSelected(activityHome.java:67)
at com.google.android.material.bottomnavigation.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:243)
at androidx.appcompat.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:840)
at androidx.appcompat.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158)
at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:991)
at com.google.android.material.bottomnavigation.BottomNavigationMenuView$1.onClick(BottomNavigationMenuView.java:124)
at android.view.View.performClick(View.java:7357)
at android.view.View.performClickInternal(View.java:7334)
at android.view.View.access$3600(View.java:808)
at android.view.View$PerformClick.run(View.java:28200)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7478)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)
activityHome.java
package com.example.sociate11;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.FirebaseAuth;
public class activityHome extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
private Button logout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
firebaseAuth = FirebaseAuth.getInstance();
logout = (Button)findViewById(R.id.btnLogOut);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firebaseAuth.signOut();
finish();
startActivity(new Intent(activityHome.this, MainActivity.class));
}
});
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation_bar);
bottomNav.setOnNavigationItemSelectedListener(navListener);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
}
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.home_fragment:
selectedFragment = new HomeFragment();
break;
case R.id.events_fragment:
selectedFragment = new EventFragment();
break;
case R.id.fragment_myconversation:
selectedFragment = new ConversationFragment();
break;
}
assert selectedFragment != null;
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
return true;
}
};
}
ConversationsFragment.java (all 3 fragments are currently identical)
package com.example.sociate11;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class ConversationFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_myconversations,container,false);
}
}
bottom_navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/menu_home"
android:title="Home"
android:icon="#drawable/ic_home"
app:showAsAction="always"/>
<item
android:id="#+id/menu_myEvents"
android:title="My Events"
android:icon="#drawable/ic_event"
app:showAsAction="always"/>
<item
android:id="#+id/menu_myConversations"
android:title="My Conversations"
android:icon="#drawable/ic_conversations"
app:showAsAction="always"/>
</menu>
activity_home.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activityHome"
android:background="#color/colorPrimary">
<Button
android:id="#+id/btnLogOut"
android:layout_width="115dp"
android:layout_height="75dp"
android:text="log out"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/bottom_navigation_bar" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground"
app:itemTextColor="#color/colorPrimaryDark"
app:itemIconTint="#color/colorPrimaryDark"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btnLogOut"
app:layout_constraintVertical_bias="1.0"
app:menu="#menu/bottom_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>
Thank you for the help as always, and please let me know if I didn't provide enough info!