Rollie
Rollie

Reputation: 4752

How do I programmatically add a ProgressBar in AsyncTask.onPreExecute?

Code in async task:

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        ScrollView sv = (ScrollView)findViewById(mScrollViewID);
        sv.removeAllViews();
        pb = new ProgressBar(mContext, null, android.R.attr.progressBarStyleSmall);
        pb.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        pb.setIndeterminate(true);
        pb.setVisibility(View.VISIBLE);

        TextView tv = new TextView(mContext);
        tv.setText("Some text here.");
        sv.addView(pb);
    }

Note the TextView at the end - if I add that to the ScrollView instead, it shows up just fine. However, I can't seem to get the ProgressBar to display anything at all. It's my first time using the control - am I missing something silly?

Edit: if it matters, the ScrollView in use is defined in XML as:

<ScrollView android:id="@+id/scrollview0" android:layout_width = "match_parent" android:layout_height="match_parent"
            android:fillViewport="true" android:padding="5dp">

Upvotes: 1

Views: 8809

Answers (2)

Mohsin Naeem
Mohsin Naeem

Reputation: 12642

if you add tv after pb it deffinatyl shows the error?

It is because a ScrollView only host one child. So what you need to add a LinearLayout in your ScrollView and then add other stuff in your Linear layout

Upvotes: 0

MAC
MAC

Reputation: 15847

This problem occurs many when you are creating ProgressBar dynamically

i suggest create one ProgressBar through xml

and set default visibility GONE

Upvotes: 3

Related Questions