Learn Android development Basic to advance using java
Splash screens
How the splash screen works
When a user launches an app while the app's process is not running (a cold start) or the Activity has not been created , the following events occur. (The splash screen is never shown during a hot start)
The system shows the splash screen using themes and any animations that you've defined.
When the app is ready, the splash screen is dismissed and the app is displayed.
Thread background = new Thread() {
public void run() {
try {
// Thread will sleep for 5 seconds
sleep(5*1000);
// After 5 seconds redirect to another intent
Intent i=new Intent(getBaseContext(),MainActivity.class);
startActivity(i);
//Remove activity
finish();
} catch (Exception e) {
}
}
};
// start thread
background.start();
Action Bar In Android
ActionBar ab = getSupportActionBar();
getSupportActionBar().hide();
getSupportActionBar().setTitle("home screen");
getSupportActionBar().setTitle("hello world");
getSupportActionBar().setLogo(R.drawable.ic_launcher_background);
ab.setSubtitle("this is my app");
ab.setDisplayShowCustomEnabled(true);
ab.setElevation(0.34f);
ab.setHideOnContentScrollEnabled(false);
ab.setHomeButtonEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_launcher_background);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Toast in Android app
Toast.makeText(MainActivity.this, "button was click", Toast.LENGTH_SHORT);
Toast.makeText(MainActivity.this, "button was click", Toast.LENGTH_LONG);
snackbar in android
Snackbar in android is a new widget introduced with the Material Design library as a replacement of a Toast. Android Snackbar is light-weight widget and they are used to show messages in the bottom of the application with swiping enabled. Snackbar android widget may contain an optional action button.
mySnackbar = Snackbar.make(binding.calculate,error,Snackbar.LENGTH_SHORT);
mySnackbar.setAction("undo", new View.OnClickListener() {
@Override
public void onClick(View view) {
mySnackbar.dismiss();
}
});
mySnackbar.show();
ProgressDialog in android
ProgressDialog progressDialog;
progressDialog = new ProgressDialog(this);
// progressDialog.setContentView(R.layout.progress_dialog);
progressDialog.setTitle("Loading");
progressDialog.show();
if(progressDialog != null){
progressDialog.dismiss();
}
How to add Onclick Listener on button in android
text = findViewById(R.id.textView4);
btn = findViewById(R.id.button8);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
text.setText("hello world");
showalert();
Toast.makeText(MainActivity.this, "button was click", Toast.LENGTH_SHORT).show();
Snackbar mySnackbar = Snackbar.make(text, "hello world", Snackbar.LENGTH_SHORT);
mySnackbar.setAction("undo", new View.OnClickListener() {
@Override
public void onClick(View view) {
mySnackbar.dismiss();
}
});
mySnackbar.show();
}
});
Alert Dialog in android with onBackPress using function
public void showalert(String title){
new AlertDialog.Builder(this).setIcon(R.drawable.ic_launcher_background).setTitle("Error")
.setMessage(title)
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
}).setNeutralButton("Help", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(notesactivity.this, "Help", Toast.LENGTH_SHORT).show();
}
}).show();
}
@Override
public void onBackPressed() {
showalert("Are you sure you want to Exit");
}
Intent
moving from one screen to another using intent
Intent intent = new Intent(MainActivity.this,ShareIntent.class);
startActivity(intent);
share text on social media
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, "Text to share.");
shareIntent.setType("text/plain");
startActivity(shareIntent);
Open phone dial after click button
// open phone Intent intent = new Intent(); intent.setAction(Intent.ACTION_DIAL); context.startActivity(intent);
// open phone
Intent intent = new Intent();
intent.setAction(Intent.ACTION_DIAL);
context.startActivity(intent);
Open url,website, youtube using Intent
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.youtube.com/watch?v=gtYpdKZjxx0")));
send text in whatsapp using intent
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.setPackage("com.whatsapp");
intent.putExtra(Intent.EXTRA_TEXT,models.getTitle());
context.startActivity(intent);
Copy text using clipManager
ClipboardManager cbManager = (ClipboardManager)(context.getSystemService(Context.CLIPBOARD_SERVICE));
ClipData clipData;
clipData = ClipData.newPlainText("text","Hello world");
cbManager.setPrimaryClip(clipData);
Send data from one screen to other screen using intent
You Can pass along data as text in the intent that start the second activity
Intent myIntent = new Intent(this, NextActivity.class);
myIntent.putExtra("text", "hello world");
startActivity(myIntent);
In the oncreate method of your profile activity you can access the text:
Intent intent = getIntent();
String text = intent.getStringExtra("text");
getSupportActionBar().setTitle("Share intent"+text);
Android ListView and Adapter
listView = findViewById(R.id.listview);
String [] city = {"Nepal","india"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
ListView_items.this, android.R.layout.simple_dropdown_item_1line,city);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(ListView_items.this, ""+city[i], Toast.LENGTH_SHORT).show();
}
});
Android RecyclearView
first create a folder models on package folder to create models right click
in package and click on package for create a folder. inside folder create a
modal inside modal create a constructor,Geter, setter etc
package com.example.firstapp.Models;
public class BookModals {
int Bookimage;
String Bookname;
public BookModals(int bookimage, String bookname) {
Bookimage = bookimage;
Bookname = bookname;
}
public int getBookimage() {
return Bookimage;
}
public void setBookimage(int image) {
Bookimage = image;
}
public String getBookname() {
return Bookname;
}
public void setBookname(String bookname) {
Bookname = bookname;
}
}
Create A adapter folder and inside adapter create file.
how to add onclick listener inside adapter
package com.example.bestnoteapp.Adapters;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.bestnoteapp.Modals.UserProfileModals;
import com.example.bestnoteapp.PdfViews;
import com.example.bestnoteapp.R;
import com.example.bestnoteapp.ScrollingDetails;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class UserProfileAdapter extends RecyclerView.Adapter<UserProfileAdapter.ViewHolder> {
ArrayList<UserProfileModals>list;
Context context;
public UserProfileAdapter(ArrayList<UserProfileModals> list, Context context) {
this.list = list;
this.context = context;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.sample_userprofile,parent,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
final UserProfileModals modals = list.get(position);
holder.profile.setImageResource(modals.getImage());
holder.name.setText(modals.getName());
holder.desc.setText(modals.getDesc());
holder.date.setText(modals.getDate());
holder.profile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Intent intent = new Intent(context, ScrollingDetails.class);
// context.startActivity(intent);
Intent intent = new Intent(context, PdfViews.class);
context.startActivity(intent);
// share to social media
// Intent intent = new Intent();
// intent.setAction(Intent.ACTION_SEND);
// intent.setType("text/plain");
// context.startActivity(intent);
// open phone
// Intent intent = new Intent();
// intent.setAction(Intent.ACTION_DIAL);
// context.startActivity(intent);
// open youtube channel
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.youtube.com/watch?v=gtYpdKZjxx0")));
}
});
}
@Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView profile;
TextView name;
TextView desc;
TextView date;
public ViewHolder(@NonNull View itemView) {
super(itemView);
profile = itemView.findViewById(R.id.profile);
name = itemView.findViewById(R.id.name);
desc = itemView.findViewById(R.id.desc);
date = itemView.findViewById(R.id.date);
}
}
}
View binding in android
View binding is a feature that allows you to more easily write code that interacts with views. Once view binding is enabled in a module, it generates a binding class for each XML layout file present in that module. An instance of a binding class contains direct references to all views that have an ID in the corresponding layout
In most cases, view binding replaces findViewById
Setup instructions
View binding is enabled on a module by module basis. To enable view binding in a module, set the viewBinding build option to true in the module-level build.gradle file, as shown in the following example:
android {
...
buildFeatures {
viewBinding true
}
}
ActivityNotesactivityBinding binding = ActivityNotesactivityBinding.
inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.toolbar);
Inside main activity now we have to add the data to the list show we create a arraylist, Adapter, and
show data using LinearLayout,GridLayout,Staggered Layour
ArrayList<UserProfileModals>list = new ArrayList<>();
list.add(new UserProfileModals(R.drawable.img,"krishna kharal",
"Hello everyone","343"));
UserProfileAdapter adapter = new UserProfileAdapter(list,this);
binding.recycler.setAdapter(adapter);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
binding.recycler.setLayoutManager(linearLayoutManager);
How to create Custom toolbar.
Choose View Customize. ...
Click the Toolbars tab.
Click New. ...
Type a name for the new toolbar, and click OK. ...
Click the Commands tab.
In the Categories list, click a menu.
From the Commands list, drag command icons to the new toolbar.
When you are finished adding commands, click Close.
Toolbar toolbar = binding.toolbar;
setSupportActionBar(toolbar);
CollapsingToolbarLayout toolBarLayout = binding.toolbarLayout;
toolBarLayout.setTitle(getTitle());
How to create toolbar menu.
This is going to be in res/menu/main_menu .
Right click the res folder and choose New > Android Resource File.
Type main_menu for the File name.
Choose Menu for the Resource type.
How to set toolbar menu items to the different screen and click
listener to the different menuitems.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menuitem, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch(item.getItemId()){
case R.id.item1:
Toast.makeText(this, "Home page", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
CountDown Timer with Runnable and Handler in android.
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
// code to execute
number++;
Toast.makeText(TaskSheduling.this, "Item count "+number, Toast.LENGTH_SHORT).show();
handler.postDelayed(this,1000);
}
};
handler.post(runnable);
new CountDownTimer(300,500){
@Override
public void onTick(long l) {
Log.d("start","start timer");
}
@Override
public void onFinish() {
Log.d("finish","finish timer");
}
}.start();
Button sheet Fragement
This example demonstrates how do I implement android button sheet widget.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Create a sample layout resource file for ButtonSheet.
Step 3 - right click in package and create Blank fragment.
Step 4 - Go to Activity and create object of BottomsheetFragment same as the Fragment name.
BottomSheetFragment bottomSheetFragment = new BottomSheetFragment();
bottomSheetFragment.show(getSupportFragmentManager(),bottomSheetFragment.getTag());
BottomSheetFragment is the Name of Fragment we have Created.
How to add Youtube video in Your android app.
binding.youtubePlayerView.addYouTubePlayerListener(new AbstractYouTubePlayerListener() {
@Override
public void onReady(@NonNull YouTubePlayer youTubePlayer) {
String videoId = "7jN0-57G0vw";
youTubePlayer.loadVideo(videoId, 0);
}
});
Demo app
Embedding Video with media Controles
Steps to embed video in your Android Application
Open your Android project and create a new Android project.
Create a new folder named "raw" in your Android project's "res" folder and place your video file inside the "raw" folder. ...
To add a video player in the activity_main. ...
Write code to attach video to the VideoView.
binding.videoView.setVideoPath("android.resource://"+ getPackageName() + "/"+ R.raw.video);
binding.videoView.start();
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(binding.videoView);
binding.videoView.setMediaController(mediaController);
MediaPlayer & Handling Audio in Android
MediaPlayer mediaPlayer = MediaPlayer.create(this,R.raw.video);
private void Playbtn(){
play.setOnClickListener(v->{
// toggle play or pause btn
// if(video.isPlaying()) {
// video.pause();
// play.setText("Pause");
// }else{
// video.start();
// play.setText("Play");
// }
mediaPlayer.start();
});
}
private void stopbtn(){
// stop.setOnClickListener(v->{
mediaPlayer.stop();
// });
}
private void Pausebtn() {
pause.setOnClickListener(v -> {
mediaPlayer.pause();
});
}
How to set different View Background Color
play = findViewById(R.id.play);
play.setBackgroundColor(Color.GREEN);
Change Volume with Seekbar in android
private void Seekbarchange() {
mediaPlayer = MediaPlayer.create(this,R.raw.video);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
seekBar.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
seekBar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,progress, 0);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
seekBar1.setMax(mediaPlayer.getDuration());
// new Timer().scheduleAtFixedRate(new TimerTask() {
// @Override
// public void run() {
// seekBar.setProgress(mediaPlayer.getCurrentPosition());
// }
// },0,900);
seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// Update the progress depending on seek bar
mediaPlayer.seekTo(progress);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
App Demo
fetch data from Firebase and show data in listview
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference().child("student");
city = new ArrayList<String>();
databaseReference.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
city = new ArrayList<String>();
for(DataSnapshot snapshot1:snapshot.getChildren()){
String data = snapshot1.getValue().toString();
city.add(data);
}
adapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1,city);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
@Override
public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
city = new ArrayList<String>();
for(DataSnapshot snapshot1:snapshot.getChildren()){
String data = snapshot1.getValue().toString();
city.add(data);
}
adapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1,city);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
@Override
public void onChildRemoved(@NonNull DataSnapshot snapshot) {
}
@Override
public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(ListViewAdapters.this, city.get(i), Toast.LENGTH_SHORT).show();
}
});
Capture Image from Camera and set the image in ImageView.
floatingactionbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, Camera_request_code);
}
});
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Camera_request_code && resultCode == RESULT_OK)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
image.setImageBitmap(photo);
}
}
select image from Gallery and set image in ImageView an also insert image in storage and real time database
FirebaseStorage storage;
FirebaseDatabase database;
database = FirebaseDatabase.getInstance();
storage = FirebaseStorage.getInstance();
// fetch image from firebase
database.getReference().child("image").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
String img = snapshot.getValue(String.class);
Picasso.get().load(img).into(binding.topimage);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(ImagePickers.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
// binding.floatingActionButton.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// Intent mycamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// startActivityForResult(mycamera, Camera_request_code);
// }
// });
launcher = registerForActivityResult(new ActivityResultContracts.GetContent(), new ActivityResultCallback<Uri>() {
@Override
public void onActivityResult(Uri uri) {
// set image into the imageView
binding.topimage.setImageURI(uri);
// upload image to the firebase storage
final StorageReference reference = storage.getReference().child("image");
reference.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(ImagePickers.this, "Image Upload Successfully", Toast.LENGTH_SHORT).show();
}
});
}
});
binding.upload.setOnClickListener(v -> {
launcher.launch("image/*");
});
}
Steps to Implement Navigation Drawer in Android
- Step 1: Create an Android Studio Project.
- Step 2: Adding a dependency to the project.
- Step 3: Creating a menu in the menu folder.
- Step 4: Working with the activity_main.xml file.
- Output UI:
- Step 5: Include the Open Close strings in the string.xml.
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.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"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DrawerActivity">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbars"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="@color/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:theme="?attr/actionBarTheme">
<TextView
android:id="@+id/toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="toggle"
/>
</androidx.appcompat.widget.Toolbar>
</androidx.constraintlayout.widget.ConstraintLayout>
<com.google.android.material.navigation.NavigationView
android:id="@+id/navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:headerLayout="@layout/header"
android:background="@color/colorPrimary"
app:menu="@menu/main_menu"
android:textAlignment="textStart"
android:layout_gravity="start"
>
</com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>
insider MainActivity
private ActionBarDrawerToggle toggle;
setSupportActionBar(binding.toolbars);
toggle = new ActionBarDrawerToggle(this,binding.drawer,binding.toolbars,R.string.open,R.string.close);
binding.drawer.addDrawerListener(toggle);
toggle.syncState();
onclick in Navigation drawer
binding.navigation.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
binding.drawer.closeDrawer(GravityCompat.START);
switch (item.getItemId()){
case R.id.share:
Toast.makeText(DrawerActivity.this, "share btn click", Toast.LENGTH_SHORT).show();
break;
}
return false;
}
});
@Override
public void onBackPressed() {
if(binding.drawer.isDrawerOpen(GravityCompat.START)){
binding.drawer.closeDrawer(GravityCompat.START);
}else{
super.onBackPressed();
}
}
Drawer Navigation app demo
How to add ImageSlider in android
allprojects { repositories { ... maven { url 'https://jitpack.io' } } } dependencies { implementation 'com.github.denzcoskun:ImageSlideshow:0.1.0' }
Add this code in xml layout
<com.denzcoskun.imageslider.ImageSlider
android:id="@+id/image_slider"
android:layout_width="match_parent"
android:layout_height="300dp"
app:iss_auto_cycle="true"
app:iss_period="2000"
app:iss_delay="2"/>
add this code in MainPage
List<SlideModel> imagelist = new ArrayList<>();
imagelist.add(new SlideModel(R.drawable.ctevt,null));
imagelist.add(new SlideModel(R.drawable.ctevt,null));
imagelist.add(new SlideModel(R.drawable.ctevt,null));
binding.imageSlider.setImageList(imagelist, ScaleTypes.FIT);
How to add pdf in android app
1) Create a assets folder and add pdf to the assets folder.
implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'
3) add these code in gradle.properties.
android.enableJetifier=true
4) add these code in setting.gradle
webview in android convert website to app in android
1) first add webview widget in xml layout.
2) create a java class WebViewController
inside main page
WebView myWebView = root.findViewById(R.id.webview);
myWebView.loadUrl("https://coderkharal.blogspot.com/");
myWebView.setWebViewClient(new WebViewController());
inside webViewController
package com.example.mylibrary.Fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import com.example.mylibrary.R;
import com.example.mylibrary.WebViewController;
public class AboutFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root = inflater.inflate(R.layout.fragment_about, container, false);
WebView myWebView = root.findViewById(R.id.webview);
myWebView.loadUrl("https://coderkharal.blogspot.com/");
myWebView.setWebViewClient(new WebViewController());
return root;
}
}
How to load image using Picasso library
Picasso.get()
.load(modals.getBookimage())
.into(holder.Bookimage);
BitMap in android
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
wallpaperManager.setBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
How to create Bottom Navigation
1) Add BottomNavigation widgets to the Activity.
2) create menu folder and add items.
3) set menu to the BottomNavigation to set menu in BottomNavigation used menu to the xml BottomNavigation.
BottomNavigation.setOnNavigationItemReselectedListener(new BottomNavigationView.OnNavigationItemReselectedListener() {
@Override
public void onNavigationItemReselected(@NonNull MenuItem item) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
switch (item.getItemId()) {
case R.id.home:
transaction.replace(R.id.containers, new HomeFragment());
break;
case R.id.search:
transaction.replace(R.id.containers, new SearchFragment());
break;
case R.id.cart:
transaction.replace(R.id.containers, new CartFragment());
break;
case R.id.settings:
Toast.makeText(MainActivity.this, "Settings Fragments", Toast.LENGTH_SHORT).show();
break;
}
transaction.commit();
}
});
}
How to used DialogPush in android
holder.edit.setOnClickListener(v->{
Toast.makeText(context, "Edit item is "+position, Toast.LENGTH_SHORT).show();
DialogPlus dialog = DialogPlus.newDialog(context)
.setContentHolder(new com.orhanobut.dialogplus.ViewHolder(R.layout.update_popup))
.setExpanded(true) // This will enable the expand feature, (similar to android L share dialog)
.create();
dialog.show();
View view = dialog.getHolderView();
EditText updatecourse = view.findViewById(R.id.updatename);
Button update = view.findViewById(R.id.update);
updatecourse.setText(models.getTitle());
});
alert dialog
QuantityDialogBinding quantityDialogBinding = QuantityDialogBinding.inflate(LayoutInflater.from(context));
AlertDialog dialog = new AlertDialog.Builder(context)
.setView(R.layout.quantity_dialog).create();
dialog.show();
date and time in android
// date in android
SimpleDateFormat d1 = new SimpleDateFormat("dd-MM-yy");
date = d1.format(calendar.getTime());
// time in android
SimpleDateFormat t1 = new SimpleDateFormat("hh:mm a");
time = t1.format(calendar.getTime());
Comments
Post a Comment