I am using AsyncTask in my application to load data from Internet. Here is onPostExecute method of my class that extends Async class.
protected void onPostExecute(Article result) {
super.onPostExecute(result);
TextView txtTitle= (TextView) view.findViewById(R.id.title);
txtTitle.setText(result.getTitle());
TextView txtMain= (TextView) view.findViewById(R.id.main);
txtMain.setText(result.getContent());
}
This is the overridden method from PageAdapter that instantiate pages. customlayout is the layout that shows article.
public Object instantiateItem(View container, int position) {
LayoutInflater inflater = (LayoutInflater) container.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View page= inflater.inflate(R.layout.customlayout , null);
Worker aw = new Worker(page, container.getContext());
aw.execute(links.get(position));
((ViewPager) container).addView(page,0);
return page;
}
Here is layout of a page that is inflated in each page.
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp" />
What I am trying to achieve is show a progress information until data loads. I should be able to swipe through page even while loading.
I would be grateful if anyone would help.
Also how can I control number of pages that are being loaded in background?
If you are looking for a spinning progress bar, you can try this:
xml:
<FrameLayout android:id="#+id/progressContainer">
<ProgressBar style="#android:style/Widget.ProgressBar.Large"
android:layout_gravity="center" />
</FrameLayout>
activity:
private View progressContainer;
#Override
public View onCreateView(...) {
progressContainer = v.findeViewById(R.id.progressContainer);
progressContainer.setVisibility(View.INVISIBLE);
}
So whenever you need to display the Progress just set the View to visible.
If you want to be able to still interact with your activity, you can just modify the clickability of the parent FrameLayout:
android:clickable="true" (or "false")
Set it to false if you want to interact, and true to block!
I recommend to use fragments as your viewPager items, and implement the loading pattern inside the fragment i.e - https://github.com/johnkil/Android-ProgressFragment
Regarding number of pages being loaded see - setOffscreenPageLimit
If I am not wrong. You are creating something like youtube video, fetching the frame on background and keep update it. In your case is book, fetching pages on background and keep update on it.
First, What you needs is fragment as you cannot destroy your AsyncTask that running on your activity.
Second, AsyncTask publishProgress and onProgressUpdate(Progress...) method, it help you to report background condition. You can take a look at the usage example provided by android
http://developer.android.com/reference/android/os/AsyncTask.html
Related
I am trying to set the visibility of a Textview depending on the response returned by Retrofit . onFailure, I am setting the visibility to visible tv_no_cat.setVisibility(View.VISIBLE); However, this does not work. I am doing the same with a ContentLoadingProgressBar and it's working appropriately. Here is my code
public void onFailure(Call<List<MoviesCategory>> call, Throwable t) {
tv_no_cat.setVisibility(View.VISIBLE); ////This does not work
Boolean x = tv_no_cat.getVisibility() == View.VISIBLE;
Toast.makeText(getContext(), "Network Error "+x, Toast.LENGTH_LONG).show(); //This shows true
tv_no_cat.setTextColor(Color.BLUE);
videoLoadingPb.setVisibility(View.GONE); //This works
}
My guess is that am trying to set the textview which is on UI thread from another thread. If so, why is it working for the ContentLoadingProgressBar?
Here is my xml for the 2 views
<android.support.v4.widget.ContentLoadingProgressBar
android:id="#+id/loading_categories"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:visibility="visible" />
<TextView
android:layout_below="#id/loading_categories"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="No Movie Category Found"
android:id="#+id/tv_no_cat"
android:textAlignment="center"
android:layout_gravity="bottom"
android:visibility="gone"
/>
Any help on how I can set the textview Visibility to VISIBLE is welcome.
From the docs:
On Android, callbacks will be executed on the main thread...
So this is not your issue, and I'm doubtful that it's related to Retrofit, especially when it works for another view. Please make sure that there are no problem in your xml design, and that there are no other methods that affect this view's visibility.
are registering Textview inside Oncreate or some where else ?
And this code you are using inside activity of fragment ?
Please check this ...
tv_no_cat=(TextView)findViewById(R.id.tv_no_cat);(Inside Activity)
tv_no_cat=(TextView)rootView.findViewById(R.id.tv_no_cat);(Inside Fragment )
The following error occurs when I attempt to inflate a layout within a ListView:
requestLayout() improperly called by android.widget.TextView{...} during layout: running second layout pass
I am attempting to inflate a layout within a ListView as follows:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) musicActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item, parent, false);
...
}else{...}
}
The layout being inflated can look as simple as the following, and will still produce the error
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/txt_size"/>
I have looked into similar questions, and no solutions found seem to work Question 1, Question 2, Question 3.
Does anyone know what causes this type of error? Any troubleshooting advice? For more context, this ListView is displayed within a Fragment within a ViewPager
UPDATE
Here is the full XML Layout (minus a bunch of attributes), that still results in the problem
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/txt2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/txt3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/txt4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
Based on this, I would think the XML itself is not a problem, unless it has to do with the fact that I am using a ViewPager and Fragments
This issue seems to be a bug in the android implementation, please see: https://code.google.com/p/android/issues/detail?id=75516
Activating the fast scroll feature of a ListView in your code via ListView.setFastScrollEnabled(true) will trigger this bug and you'll start seeing the
requestLayout() improperly called by android.widget.TextView{...}
during layout: running second layout pass
message in your console.
This bug must have been introduced in one of the KitKat (4.4.x) updates, as I've not seen it with the initial KitKat (4.4.0) release. Apart from the ugly console spamming with the debug message from above, there seem to be no other impacts (maybe performance in some cases, which I haven't tested).
Cheers
PS: it's not the first time that the fast scroll feature is bugged, e.g. https://code.google.com/p/android/issues/detail?id=63545, 63545 was fixed in KitKat 4.4.3 but 75516 poped up thereafter --> seems to be a vexed subject for google ;-)
EDIT May 12 2015:
I updated my Nexus 7 to Android 5.1 some minutes ago (was Running 5.0 before) and stopped seeing this issue in this new version. As the appearance of the FastScroll indicator also changed in 5.1, I assume that google fixed this issue or at least commented out those ugly lines that spammed the console...
75516 & 82461 are still 'unresolved', but I guess that those refer to the same issue, that's now resolved in 5.1.
The problem is that while the method getView() of your adapter is displaying your layout some other code is trying to access this view to display it, resulting in a collision.
Note that some methods, that maybe you don't take care of (like setScale(), setTypeFace()) indeed call requestLayout(), so it would be interesting what you are doing after your inflate statement.
For me this issue was occurring upon a setLayoutParams() call. The solution was posting a runnable on the looper:
// java
imageView.post(new Runnable() {
#Override public void run() {
imageView.setLayoutParams(params);
}
});
// kotlin
post(Runnable { imageView.setLayoutParams(params) })
I fixed this issue by disabling fastScroll on the ListView in the XML.
<ListView
android:id="#+id/mListview"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:fastScrollEnabled="false"
/>
In my case (Samsung Galaxy S4, API 21) this happened in ListView with EditTexts. I have a listener for field validation. Something like:
edit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
error.setVisibility(View.INVISIBLE);
error.setText("");
} else {
String s = edit.getText().toString();
if (s.isEmpty()) {
error.setText("Error 1");
} else if (s.length() < 2 || s.length() > 100) {
error.setText("Error 2");
}
error.setVisibility(View.VISIBLE);
}
}
});
After settinging focus in one of these EditTexts an above check is called. After that a TextView will change (the TextView contains an error message and lies over the EditText).
Setting focus to the second or the third EditText led to permanent request of the first EditText and return to current. An applications runs in infinite loop of requests (focus edittext 1, unfocus edittext 1, focus 3, unfocus 3, focus 1, etc).
I tried to set listView.setFastScrollEnabled(false). Also I tried a requestLayout() of some elements like in https://github.com/sephiroth74/HorizontalVariableListView/issues/93 with no chances.
Currently I made that TextView of fixed width and height in XML:
<TextView
android:id="#+id/error"
android:layout_width="match_parent" (or "200dp", but not "wrap_content")
android:layout_height="20dp"
.../>
After some experiments I noticed that a height of 20dp can be replaced with "wrap_content". But if a text is too long that divides into 2 lines, the application again catches in the infinite loop. So, android:singleLine="true" will help. It is deprecated, but amazingly android:maxLines="1" with android:lines="1" don't help as they again request layout.
Eventually we have:
<TextView
android:id="#+id/error"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:textColor="#f00"
android:textSize="20sp"
tools:text="Error message"/>
That's not a good solution, but at least it breaks the infinite loop.
This might happen if you are using some 3rd party extension of ListView. Replace that with standard ListView and check if it still throws the error.
I had similar problem. Please check Android layout: running second layout pass and my answer.
I had the same issue with Kitkat 4.4.4 on Motorola X with Genymotion. In my case the list item is a simple CheckedTextView and the error occurred in AppCompatCheckedTextView.
As a normal implementation I inflated the item from XML layout file like below:
if (convertView == null) {
convertView = inflater.inflate(R.layout.checkable_list_entry, parent, false);
}
After some trying I found out that this has something to do with XML inflation. I don't know the root cause, but as a solution I decided to inflate the list item by code and set all the properties by code too.
It ended up like this:
CheckedTextView view;
if (convertView == null) {
view = new CheckedTextView(parent.getContext());
view.setMinHeight(getResources().getDimensionPixelSize(R.dimen.default_touch_height));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
view.setTextAppearance(R.style.SectionEntry);
} else {
view.setTextAppearance(parent.getContext(), R.style.SectionEntry);
}
view.setBackgroundResource(R.drawable.form_element);
view.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
view.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT));
} else {
view = (CheckedTextView) convertView;
}
I had a problem with the same warning log :
requestLayout() improperly called by android.support.v7.widget.AppCompatTextView {...} during layout: running second layout pass
I was working with recylcerview and going to update it with new data.
The only solution that worked for me is as below :
Step(1). Remove current data :
public void removeAll() {
items.clear(); //clear list
notifyDataSetChanged();
}
Step(2). When you want to populate the recyclerview with new data, first set a new LayoutManager to recyclerview again:
private void initRecycleView() {
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false));
}
Step(3). Update the recyclerview with new data. for example :
public void refreshData(List newItems) {
this.items = newItems;
notifyItemRangeChanged(0, items.size());
}
Try taking off the textSize from the xml and setting it in Java code. I think that's causing it to be laid out twice.
In my case this warning prevented a button from showing up in API 21 devices. The button visibility was previously set to GONE.
The only workaround I got it was setting to INVISIBLE instead of GONE for API 21. It wasn't a real solution but it was acceptable for me.
I only post this because it can be useful from somebody.
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
theButton.setVisibility(View.INVISIBLE);
}
else {
theButton.setVisibility(View.GONE);
}
Sometimes you maybe already fixed the issue but it still keeps same error, so you need to close visual studio then delete all bin and obj folders from your projects, then uninstall the app from the emulator. then walah!! everything will works fine
I solved the problem like this:
mHolder.txt_fword.setTextSize(22);
mHolder.txt_farth.setTextSize(22);
mHolder.txt_fdef.setTextSize(22);
mHolder.txt_fdef2.setTextSize(22);
mHolder.txt_frem.setTextSize(22);
//if (fdef2.get(pos).equals("")) mHolder.txt_fdef2.setVisibility(View.GONE);
//if (frem.get(pos).equals("")) mHolder.txt_frem.setVisibility(View.GONE);
issue is .setVisibility(View.GONE); , change to .setVisibility(View.VISIBLE);
Found a Solution!
I now use a ViewPager instead of a ViewFlipper.
The Views are now generated within my run() method (which is already there because I fetch data from the web) and saveed in a Map.
In my Handler I only call pagerAdapter.notifyDataSetChanged() the pagerAdapter uses the Map of views and it works smooth and fast.
So I'm now looking for a away to have the ViewPager scroll endless, but thats another problem not connected to this one ;)
Thank all of you for your answers and keep up the good support.
I'm quite new to Android development and facing a problem while inflating a (huge) layout.
I getting some Data from a Webservice which works fine then i'm using a handler within my Activity to bring this data to the frontend. Here is my handleMessage:
public void handleMessage(Message msg) {
LayoutInflater inflater = getLayoutInflater();
List<Integer> gamedays = new ArrayList<Integer>(games.keySet());
Collections.sort(gamedays);
for (Integer gameday : gamedays) {
View gamedaytable = inflater.inflate(R.layout.gamedaytable, null);
TableLayout table = (TableLayout) gamedaytable.findViewById(R.id.gameDayTable);
table.removeAllViews();
List<Game> gamelist = games.get(gameday);
int rowcount = 2;
for (Game game : gamelist) {
View tableRow = inflater.inflate(R.layout.gamedayrow, null);
TextView homeTeam = (TextView) tableRow.findViewById(R.id.gameDayHome);
TextView awayTeam = (TextView) tableRow.findViewById(R.id.gameDayAway);
TextView gameResult = (TextView) tableRow.findViewById(R.id.gameDayResult);
gameResult.setBackgroundResource(R.drawable.resultbackground);
homeTeam.setText(game.getHomeTeam().getName());
awayTeam.setText(game.getAwayTeam().getName());
if (game.getHomegoals() < 0 || game.getAwaygoals() < 0) {
gameResult.setText("-:-");
} else {
gameResult.setText(game.getHomegoals() + ":" + game.getAwaygoals());
}
if (rowcount % 2 == 0) {
tableRow.setBackgroundColor(0xffdee0dd);
} else {
// setting alternative background
tableRow.setBackgroundColor(0xfff1f3f0);
}
rowcount++;
table.addView(tableRow);
}
flipper.addView(gamedaytable);
}
flipper.setDisplayedChild(thisgameday - 1);
pd.dismiss();
}
My Problem is that this code runs quite slow and d the processdialog freezes for about 1 second before it disappears and the layout is shown.
games consists of 34 entries which contains 9 entries by itself.
So I'm adding 34 Views consisting of a relativeLayout () which holds the table
I think the problem is, that android starts to draw and calculte the layout and this takes too long.
If I'm correct i can not use AsynTask because i can not do UI stuff there and im doing UI stuff only.
I looking for a way to have the process dialog not freezing while doing this.
Or maybe I'm doing some completly wrong
R.layout.gamedaytable:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff1f3f0"
android:focusableInTouchMode="false" >
<TableLayout
android:id="#+id/gameDayTable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:focusableInTouchMode="false" >
</TableLayout>
</RelativeLayout>
R.layout.gamedayrow:
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tableRow1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:focusableInTouchMode="false"
android:paddingBottom="5dp"
android:paddingTop="5dp" >
<TextView
android:id="#+id/gameDayHome"
style="#style/textsizeSmallScreen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="Mannschaft 1" />
<TextView
android:id="#+id/textView2"
style="#style/textsizeSmallScreen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text=":" />
<TextView
android:id="#+id/gameDayAway"
style="#style/textsizeSmallScreen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Mannschaft 2" />
<TextView
android:id="#+id/gameDayResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="5dp"
android:background="#drawable/resultbackground"
android:paddingLeft="10dip"
android:text="0:5"
android:textColor="#FFFFFF"
android:textSize="11dp"
android:textStyle="bold"
android:typeface="monospace" />
</TableRow>
Additional Info:
This is how the Table should look like.
So i'm not sure if this should really be a ListView because for me its tabledata ;)
table
You seem to be building a list, you should probably look at using a ListView, which'll have the advantages of only needing to build the UI for the number of rows currently being shown, and to also do view re-use, so that you don't need to inflate as many rows.
Found a Solution!
I now use a ViewPager instead of a ViewFlipper. The Views are now generated within my run() method (which is already there because I fetch data from the web) and saveed in a Map. In my Handler I only call pagerAdapter.notifyDataSetChanged() the pagerAdapter uses the Map of views and it works smooth and fast. So I'm now looking for a away to have the ViewPager scroll endless, but thats another problem not connected to this one ;)
Thank all of you for your answers and keep up the good support.
It is better to go for Listview. Even we can add more than one design of rows in the listview in an optimized manner which will improves the performance better.
You definitely can do this on an AsyncTask. While you cannot update the UI on the doInBackground method of an AsyncTask, you can from the onProgressUpdate.
I would break up the code so you are iterating through items while in doInBackground, call publishProgress for each item, and then do the UI updates for the item when you get a callback in onProgressUpdate.
I am developing an Android Application. In this application, Logo bar is shown on all pages(Activities) or we can say it has header on all pages.
This Logo Bar have few icons like Home, Login, Notification, etc. and on Clicking on these icons corresponding navigation will perform.
for example if user is any where in application and click on home icon, he will navigate to the home page of application.
I am able to inflate logobar.XML into my All Activity by coding. but problem is i have to call onClickListener on all pages for all icons in Logo Bar.
This is not a good programming way.
How can i implement Logo Bar Activity in all other activity without repeating of code?
Is android have any Master Page concept as in .Net or tiles concept as in Struts?
Please guide me.
Edit: ok i got it. may be this answer will help you.
Try using Tab widget with tabactivity check this link for using fragment and tab http://developer.android.com/reference/android/app/TabActivity.html for android. i think for lower versions also we can use this. this si what the link says - "you can use the v4 support library which provides a version of the Fragment API that is compatible down to DONUT."
you have to create your masterLayout in xml and that you have to include it in your other
layouts in which you have to have it.
The solution was pretty easy.
You need to extends "Activity" Class,in onCreate function SetContentView to your base xml layout and also need to override setContentView in base Activity Class
For Example:
1.Create "base_layout.xml" with the below code
<?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"
android:background="#000000"
android:padding="15dp" >
<LinearLayout android:orientation="horizontal" android:background="#000000"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:minHeight="50dp" android:paddingLeft="10dp">
<ImageView android:layout_width="wrap_content" android:id="#+id/ImageView01"
android:adjustViewBounds="true" android:layout_height="wrap_content"
android:scaleType="fitCenter" android:maxHeight="50dp" />
</LinearLayout>
<LinearLayout android:id="#+id/linBase"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</LinearLayout>
</LinearLayout>
2.Create "BaseActivity.java"
public class BaseActivity extends Activity {
ImageView image;
LinearLayout linBase;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.base_layout);
image = (ImageView)findViewById(R.id.ImageView01);
image.setImageResource(R.drawable.header);
linBase = (LinearLayout)findViewById(R.id.linBase);
}
#Override
public void setContentView(int id) {
LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(id, linBase);
}
}
and
public class SomeActivity extends BaseActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.some_layout);
//rest of code
}
}
The only thing I noticed so far was that when requesting a progress bar (requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS)) this needs to be done before calling super.onCreate. I think this is because nothing can be drawn yet before calling this function.
This worked great for me and hopefully you will find this useful in your own coding.
There is something like that, but only available on api 11+ (3.2 and Android 4.0.x Ice Cream Sandwich). Its called actionbar ( http://developer.android.com/reference/android/app/ActionBar.html).
I have done this using XML file.
I am just creating runtime view from XML file , and add it to the Activity layout.
I have created method for that
public static void setLoginview(Context ctx, RelativeLayout layout) {
LayoutInflater linflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View myView = linflater.inflate(R.layout.loginheader, null);
layout.addView(myView);
try {
layout.getChildAt(0).setPadding(0, 50, 0, 0);
} catch (Exception e) {
}
}
ctx is the application contetx and layout is the layout in which i want to add that view.
What I would like to accomplish is to, at runtime, place a button in the middle of the screen, as the very top layer, overlaying anything below it. (It's not big, so it will not completely cover the screen, just whatever happens to be below it.)
I looked at creating a custom dialog, however that blocks all other user input. I want all of the views below this new button to act normally and respond to the user, but I just want to add (and later remove) the button above everything.
Hopefully that makes sense. I'm just wondering what might be the best approach to look into?
Use a FrameLayout, with the button as it's 2nd child. Set it to GONE when you don't want it visible.
I had to overlay a simple layout programmatically on top of any visible activity. Normal activity layout xmls don't know anything about the overlay. Layout had one textview component but could have any structure you see fit. This is my overlay layout.
res/layout/identity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/identitylayout"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_centerInParent="true" >
<TextView
android:id="#+id/identityview"
android:padding="5dp"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textColor="#FFFFFF" android:background="#FF6600"
android:textSize="30dp"
/>
</RelativeLayout>
Overlay is shown on top of the existing content, after timeout is deleted from the screen. Application calls this function to display overlay.
private void showIdentity(String tag, long duration) {
// default text with ${xx} placeholder variables
String desc = getString(R.string.identity);
desc = desc.replace("${id}", reqId!=null ? reqId : "RequestId not found" );
desc = desc.replace("${tag}", tag!=null ? tag : "" );
desc = desc.trim();
// get parent and overlay layouts, use inflator to parse
// layout.xml to view component. Reuse existing instance if one is found.
ViewGroup parent = (ViewGroup)findViewById(R.id.mainlayout);
View identity = findViewById(R.id.identitylayout);
if (identity==null) {
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
identity = inflater.inflate(R.layout.identity, parent, false);
parent.addView(identity);
}
TextView text = (TextView)identity.findViewById(R.id.identityview);
text.setText(desc);
identity.bringToFront();
// use timer to hide after timeout, make sure there's only
// one instance in a message queue.
Runnable identityTask = new Runnable(){
#Override public void run() {
View identity = findViewById(R.id.identitylayout);
if (identity!=null)
((ViewGroup)identity.getParent()).removeView(identity);
}
};
messageHandler.removeCallbacksAndMessages("identitytask");
messageHandler.postAtTime(identityTask, "identitytask", SystemClock.uptimeMillis()+duration);
}
Timer messageHandler is member of main Activity instance (private Handler messageHandler) where I put all scheduled tasks. I am using Android 4.1 device lower than that I don't know what happens.