I wrote below method to show progress bar but the progress bar rounded by white box fits the screen width and i do not know why.
public void showProgressBar() {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
ProgressBar pbar = new ProgressBar(activity, null,
android.R.attr.progressBarStyleLargeInverse);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(30, 50);
pbar.setLayoutParams(params);
builder.setView(pbar);
builder.setCancelable(true);
progressBar = builder.create();
progressBar.show();
}
when execute the above method the progress shown as this image.
progress bar problem
How i can solve this issue?
You should use a ProgressDialog and no, it doesn't fit the screen width.
ProgressDialog pd=new ProgressDialog(activity);
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
This should give you what you want.
Do this:
ProgressDialog pd;//declare as a global variable
public void showProgressBar() {
pd=new ProgressDialog(activity);
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
}
Dismiss the ProgressDialog wherever you want later.
I solved it by stupid way but it works fine at me.
public abstract class AbstractScreen implements IActivity {
protected Response response;
protected FragmentActivity activity;
private CustomProgressDialog progress;
public AbstractScreen(FragmentActivity activity) {
this.activity = activity;
}
public abstract void loadScreen();
#Override
public void preExecution() {
// TODO Auto-generated method stub
}
#Override
public void postExecution(Response response) {
// TODO Auto-generated method stub
}
public void showProgressBar() {
progress = new CustomProgressDialog(activity);
progress.show();
}
public void closeProgress() {
progress.dismiss();
}
public FragmentActivity getActivity() {
return activity;
}
private class CustomProgressDialog extends Dialog {
private Context context;
public CustomProgressDialog(Context context) {
super(context);
this.context = context;
loadScreen();
}
public void loadScreen() {
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.progress);
setCancelable(false);
}
}
}
add this layout file also.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:orientation="vertical"
android:layout_marginRight="-7dp"
>
<ProgressBar
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="?android:attr/progressBarStyleLarge"
android:id="#+id/progressbar"
android:layout_gravity="center_horizontal"
android:max="100"
/>
</LinearLayout>
Related
Let's say I have this code:
XML
<FrameLayout android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android" >
<android.support.v7.widget.RecyclerView
android:id="#+id/photo_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
Program
private class FetchItemsTask extends AsyncTask<Void, Void, List<GalleryItem>> {
private String mQuery;
public FetchItemsTask(String query) {
mQuery = query;
}
#Override
protected List<GalleryItem> doInBackground(Void... params) {
if (mQuery == null) {
return new FlickrFetchr().fetchRecentPhotos();
} else {
return new FlickrFetchr().searchPhotos(mQuery);
}
}
#Override
protected void onPostExecute(List<GalleryItem> galleryItems) {
mItems = galleryItems;
setupAdapter();
}
}
How do I implement a spinning ProgressBar and hide the RecyclerView while the AsycnTask does its work in the background? Sorry if this seems like a simple question, but the only answers that I've found use ProgressDialog, which is deprecated as of API 26. Thank you in advance.
Override the Pre-execute Method and show the progress dialog.
You can show the spinner in onPreExecute() and hide it in onPostExecute().
class Your_Class extends AsyncTask<...>
{
ProgressBar pb;
Your_Class(){
// initialize pb
}
Protected void onPreExecute(){
// show progressbar
}
protected void onPostExecute(Bitmap image){
// hide progressbar
}
}
When making a custom component for Android, as far as I understood, I need:
one xml file with the layout for the component;
one java class.
Tried to make one, just for practice. Use two progressbars and one button in the XML, and create the class, than tried out in my main activity, worked fine.
But now I'm loking how to set OnClickListener on my button through the activity, and in this part I'm lost.
My loading_button.xml:
<merge
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RelativeLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="4dp"
android:progress="0"
android:id="#+id/pg_top" />
<Button
android:text="Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btn_ok"
android:background="#color/colorPrimary"
android:textColor="#ffffff"
android:layout_below="#+id/pg_top"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="5dp"
android:progress="0"
android:id="#+id/pg_bottom"
android:layout_below="#+id/btn_ok"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
</merge>
Here the LoadingButton.java:
public class LoadingButton extends RelativeLayout{
private ProgressBar pbTop;
private ProgressBar pbBottom;
private Button btnOk;
private int pbTopProgress = 0;
private int pbBottomProgress = 0;
public LoadingButton(Context context, AttributeSet attrs) {
super(context, attrs);
View view = View.inflate(context, R.layout.loading_button, this);
btnOk = (Button) view.findViewById(R.id.btn_ok);
pbTop = (ProgressBar) view.findViewById(R.id.pg_top);
pbBottom = (ProgressBar) view.findViewById(R.id.pg_bottom);
btnOk.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Doing stuff ok
}
});
}// LoadingButton
}
The setOnClickListener in the class works, but how can I set it from my main activity?
MainActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// My new component (it's id in activity_main.xml is 'lb')
LoadingButton lb = (LoadingButton) findViewById(R.id.lb);
// QUESTION - how to make something like this with btnOk:
lb.btnOkSetOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Do stuff
}
});
}
}
If this is possible, how?
If not, what is the right approach to make a custom component and set clickListeners on specific element of this component?
Best approach to handle all view click in LoadingButton (For custom view). And create interface.
public class LoadingButton extends RelativeLayout {
public interface OnLoadingButtonClickListener{
void onLoadingButtonClickListener();
}
private ProgressBar pbTop;
private ProgressBar pbBottom;
private Button btnOk;
private int pbTopProgress = 0;
private int pbBottomProgress = 0;
private OnLoadingButtonClickListener mONOnLoadingButtonClickListener;
public LoadingButton(Context context, AttributeSet attrs) {
super(context, attrs);
View view = View.inflate(context, R.layout.loading_button, this);
btnOk = (Button) view.findViewById(R.id.btn_ok);
pbTop = (ProgressBar) view.findViewById(R.id.pg_top);
pbBottom = (ProgressBar) view.findViewById(R.id.pg_bottom);
btnOk.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mONOnLoadingButtonClickListener != null){
mONOnLoadingButtonClickListener.onLoadingButtonClickListener();
}
}
});
}// LoadingButton
public void setOnLoadingClickListener(OnLoadingButtonClickListener onLoadingClickListener){
mONOnLoadingButtonClickListener = onLoadingClickListener;
}
}
And implement OnLoadingButtonClickListener in your activity.
public class MainActivity extends AppCompatActivity implements LoadingButton.OnLoadingButtonClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// My new component (it's id in activity_main.xml is 'lb')
LoadingButton lb = (LoadingButton) findViewById(R.id.lb);
lb.setOnLoadingClickListener(this);
}
#Override
public void onLoadingButtonClickListener() {
//do your stuff on ok button click
}
}
Override setOnClickListener(OnClickListener listener) in your custom Java class. Inside it, write:
btnOk.setOnClickListener(listener);
where listener is an argument of your custom view's setOnClickListener() function.
That will make your whole view clickable and click on your button will be performed. Of couse add android:clickable="true" to your custom view's root layout.
In the component
class Example #JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0,
defStyleRes: Int = 0) : ConstraintLayout(context, attrs, defStyle) {
var clickListener: () -> Unit = { }
init { }
private fun initListeners() {
binding.button.onClick {
clickListener()
}
}
In the activity / fragment
component.clickListener = { }
And the best part, you can send data on the component and receive it in the landa
I have this working function that load image from url. The only thing is that it shows no progress while loading the image just the screen become dimmer and after some time only the picture is shown. This makes the user think like it is not working. So how do I add progress dialog while the image is loading or any way that shows the image is loading?
public void showImage() {
Dialog builder = new Dialog(this);
builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
builder.getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
//nothing;
}
});
ImageView imageView = new ImageView(this);
Picasso.with(this).load("http://camranger.com/wp-content/uploads/2014/10/Android-Icon.png").into(imageView);
builder.addContentView(imageView, new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
builder.show();
}
try adding PlaceHolder
add this to layout folder
<RelativeLayout
android:id="#+id/hoteldetails_myContainer"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ProgressBar
android:id="#+id/hoteldetails_progressBar"
style="?android:attr/progressBarStyleSmall"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="center"
android:visibility="gone"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp" />
<ImageView
android:id="#+id/hoteldetails_imageView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY"/>
</RelativeLayout>
and this to loading code
Picasso.with(this)
.load(hoteImageStr)
.error(R.drawable.loading)
.into(img, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
if (progress != null) {
progress .setVisibility(View.GONE);
}
}
#Override
public void onError() {
}
});
public void showImage() {
Dialog builder = new Dialog(this);
builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
builder.getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
//nothing;
}
});
final ProgressDialog progressDialog = new ProgressDialog(this);
ImageView imageView = new ImageView(this);
Picasso.with(this)
.load("http://camranger.com/wp-content/uploads/2014/10/Android-Icon.png")
.into(imageView, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
// The image has loaded you can make the progress bar invisible
if (progressDialog.isShowing())
progressDialog.dismiss();
}
#Override
public void onError() {
// Show some error message
if (progressDialog.isShowing())
progressDialog.dismiss();
}
});
builder.addContentView(imageView, new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
builder.show();
progressDialog.setMessage("please wait");
progressDialog.setCancelable(false);
progressDialog.show();
}
I want to change image after some animation to first image. I am trying with this code but only the second image is getting animated. First image is not displaying.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
anim();
}
#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;
}
public void anim() {
Animation animfadein =AnimationUtils.loadAnimation(this,R.anim.fadein);
Animation animfadeout =AnimationUtils.loadAnimation(this,R.anim.fadeout);
findViewById(R.id.imageView1).startAnimation(animfadein);
findViewById(R.id.imageView1).startAnimation(animfadeout);
Context myActivity =getApplicationContext();
Toast.makeText(myActivity, "Please wait", Toast.LENGTH_SHORT).show();
button();
}
public void button() {
ImageView imgView1 = (ImageView)findViewById(R.id.imageView1);
Drawable myDrawable = getResources().getDrawable(R.drawable.start);
imgView1.setImageDrawable(myDrawable);
}
}
My xml file is like this
<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"
android:background="#drawable/background"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ImageView
android:id="#+id/imageView1"
android:contentDescription="#string/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_logo"/>
</LinearLayout>
I tried using setImageresource still same first image is not displaying.
Please let me know what mistake i have done.Thanks in advance :)
You are running everything in onCreate which is done before the user is even able to see any of the UI. It is until onStart that the user will see the UI. even so, the change will be almost immediate, so you might want to wait a few secs. Try this:
#Override
protected void onStart() {
super.onStart();
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(5000);
runOnUiThread(new Runnable() {
#Override
public void run() {
anim();
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
In general you are making a thread wait 5 secs then do the animation. I am not going to go over what's the best way to do this, but you certainly need to modify this on the UI thread, so I included it in the snippet.
For more information about threading go here:
http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html
You will need to use animation listener for achieving this:
animFadeIn.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationEnd(Animation animation) {
//start animFadeOut Here
}
});
Hope this helps.
I have a code like the below:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ProgressBar
android:id="#+id/progressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
BasicViews2Activity.java
public class BasicViews2Activity extends Activity
{
static int progress;
ProgressBar progressBar;
int progressStatus = 0;
Handler handler = new Handler();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progress = 0;
progressBar = (ProgressBar) findViewById(R.id.progressbar);
//---do some work in background thread--
new Thread(new Runnable()
{
public void run()
{
//---do some work here--
while (progressStatus < 10)
{
progressStatus = doSomeWork();
}
//---hides the progress bar---
handler.post(new Runnable()
{
public void run()
{
progressBar.setVisibility(View.GONE);
}
});
}
//---do some long running work here--
private int doSomeWork()
{
try {
Thread.sleep(500);
} catch (InterruptedException e)
{
e.printStackTrace();
}
return ++progress;
}
}).start();
}
}
Why did we use two runnable objects inside the thread class to cancel the progressbar? Couldn't we do it inside the first runnable obj – just after while loop, without another object?
The asyncTask class can be used easily with progressbars. AS they have an onPreexecute and onPostexecute with which we can update the ui thread from the background activity.
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("waiting 5 minutes..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
Then write an async task to update progress..
private class DownloadZipFileTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... urls) {
//Copy you logic to calculate progress and call
publishProgress("" + progress);
}
protected void onProgressUpdate(String... progress) {
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String result) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
Hope this makes your code easier...
#shaon007 sorry for late post, Yes you can do it with single runnable class
Like below
create your xml just the way you have created
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ProgressBar
android:id="#+id/progressbar"
android:visibility="invisible"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Keep visibility option invisible for the start
Then in your mainActivity you have to do three things those are
1) Create Handler object
2) Create anonymous runnable class
3) Call run() method from runnable with setting your progressbar visibility
As follows
public class MainActivity extends AppCompatActivity {
Handler handler;
private ProgressBar progressBar;
private int checkCount = 5000; // counter for progressbar visibility
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressbar);
handler = new Handler(); // handler object
// runnable class
final Runnable runnable = new Runnable() {
#Override
public void run() {
progressBar.setVisibility(View.VISIBLE);
checkCount -= 1000;
if(checkCount > 0) {
handler.postDelayed(this,1000);
}
else {
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(MainActivity.this,"Progress bar invisible",Toast.LENGTH_SHORT).show();
// Or your other work
}
}
};
handler.postDelayed(runnable,1000); // will start run() method after 1 second
}
}
And your done