xml:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_table"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</TableLayout>
Activity sample code:
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
TableLayout tl = (TableLayout) findViewById(R.id.main_table);
TableRow trHead = new TableRow(this);
trHead.setId(10);
trHead.setBackgroundColor(Color.GRAY);
trHead.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
TextView col1Header = new TextView(this);
col1Header.setText("Time");
col1Header.setTextColor(Color.CYAN);
trHead.addView(col1Header);
TextView col2Header = new TextView(this);
col2Header.setText("Company");
col2Header.setTextColor(Color.CYAN);
col2Header.setGravity(Gravity.END);
trHead.addView(col2Header);
tl.addView(trHead, new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
for (int i = 0; i < 3; i++) {
TableRow row = new TableRow(this);
row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
TextClock clock = new TextClock(this);
row.addView(clock);
TextView data = new TextView(this);
data.setText("dev" + 1);
data.setGravity(Gravity.END);
row.addView(data);
tl.addView(row, new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
SystemClock.sleep(1000);
}
}
}
}
SystemClock.sleep(1000); does not fulfil my need.
Whole table is appering on UI after 3 seconds. But I want rows to be added after 1 minute on the UI.
Whole table apper after 3 seconds because SystemClock.sleep receive miliseconds as parameters. (1 minute = 60000 miliseconds).
Another way to do it is using a Runnable
Runnable r = new Runnable() {
public void run() {
//Add row
}
};
Call runnable:
Handler handler = new Handler();
handler.postDelayed(r, 60000);
The problem is that you are sleeping inside of onCreate(). This blocks the UI thread so nothing will be rendered until after sleep() returns. This means that the database will be updated and rendered almost immediately. To perform an actual delay, you need to use concurrency of some type. At the lowest level, you can create a new Thread or Runnable. At a higher level, you can use AsyncTask. There are also even higher level abstractions available, but these two options should get you started in the right direction.
for(int i=1;i<=3;i++){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
//add row
}
});
}
},i*60000);
}
Related
I'm a beginner in android. I have an image button and I want it to change after 5sec .first I wrote params and table then call image button with the first pic then I call sleep method and change pic in that but when I run this code, the first pic doesn't show. Where is my problem?
Thanks
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
ViewGroup.LayoutParams superparams =
new TableLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
TableLayout supertable = new TableLayout(this);
supertable.setLayoutParams(superparams);
supertable.setOrientation(TableLayout.VERTICAL);
TableRow table = new TableRow(this);
ViewGroup.LayoutParams params =
new TableRow.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f);
ImageButton ib2 = new ImageButton(this);
ib2.setImageResource(R.drawable.ic_launcher);
ib2.setLayoutParams(params);
setContentView(supertable);
supertable.addView(table);
table.addView(ib2);
try {
Thread.sleep(5000);
ib2.setImageResource(R.drawable.star_launcher);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Sleeping the main thread is usually a bad idea as it would also freeze all the UI of the app.
You can use Handlers to achieve that without the UI freezing
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 5s
}
}, 5000);
I have TableLayout with 2 buttons and some textView
I added rows dynamically from sq-lite with these codes and it works:
TableLayout tbl
= (TableLayout) Vfood.findViewById(R.id.frag_food);
///
///somecode
///
dbfood.open();
Cursor cursor = dbfood.getGroupFood(group_Name);
int i = 1;
if (cursor.moveToFirst()) {
do {
TableRow tr = new TableRow(getActivity());
tr.setId(i);
//btnAdd
final Button btnAddDeser = new Button(getActivity());
btnAddDeser.setText("add");
btnAddDeser.setId(i);
TableRow.LayoutParams trParams1
= new TableRow.LayoutParams(65, TableRow.LayoutParams.MATCH_PARENT);
btnAddDeser.setGravity(Gravity.LEFT);
btnAddDeser.setTextSize(10);
btnAddDeser.setPadding(30, 10, 10, 10);
btnAddDeser.setMaxWidth(65);
btnAddDeser.setMinimumWidth(70);
//my problem>
btnAddDeser.setOnClickListener(mListener);
//
tr.addView(btnAddDeser, trParams1);
// Count
final TextView trCount = new TextView(getActivity());
trCount.setText(cursor .getString(3));
trCountDeserc.setId(i);
trCount.setTextColor(Color.BLACK);
trCount.setGravity(Gravity.RIGHT);
trCount.setTextSize(10);
trCount.setPadding(10, 10, 10, 15);
trCount.setClickable(true);
tr.addView(trCount);
///
///other text View
///some code
tbl.addView(tr,
new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
i++;
} while (cdeser.moveToNext());
}
dbDeser.close();
return Vfood;
}
private OnClickListener mListener = new OnClickListener() {
#Override
public void onClick(View v) {
//
//I dont know what shoud i do !
//
}
};
I just want to increase trCount one digit when user click on button.
can anyone help me?
I am new to android.
thanks
You just add this Button click event in your loop
btnAddDeser.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String str=trCount.getText().toString();
Toast.makeText(getActivity(), str, Toast.LENGTH_LONG).show();
}
});
I have an activity with a Button and a GridLayout with many children. If I add all these children in onCreate() my activity appears on a screen with a lag:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout main = new LinearLayout(this);
main.setOrientation(LinearLayout.VERTICAL);
Button button = new Button(this);
button.setText("test");
main.addView(button);
GridLayout testGrid = new GridLayout(this);
testGrid.setColumnCount(5);
for (int i = 0; i < 100; i++)
testGrid.addView(new Button(this));
main.addView(testGrid);
setContentView(main);
}
But I want at least my Buttton to appear immediately, so I try to add the children to the grid in a thread. After experiments I came to this solution:
final GridLayout testGrid = new GridLayout(this);
testGrid.setColumnCount(5);
main.addView(testGrid);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 100; i++)
MyActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
testGrid.addView(new Button(testGrid.getContext()));
}
});
}
}).start();
}
}, 1);
But I'm not sure it's a good idea, because it looks kinda complicated and may be it won't work well on some devices. Any better suggestions?
When you have to do something like this, it is a clear indication that you do something wrong. If you really need 100 buttons in a grid, maybe you should consider using GridView instead of GridLayout and loading buttons into view via a simple adapter.
I have a LinearLayout that gets populated with TextViews. Each of those TextViews gets set with the same OnClickListener. The Listener DOES get triggered, but only on the SECOND time the Activity loads.
How can I get it to trigger the first time through / why is it not triggering the first time?
public static void loadArticlesIntoSimilarList(Context mContext, String myid)
{
//POPULATES THE LIST OF ARTICLES
//associatedArticles = articlesDataSource.getAssociatedArticlesData(articleId);
for(final Article similarArticle : articlesDataSource.getAssociatedArticlesList(myid))
{
TextView similarArticleTextView = new TextView(mContext);
similarArticleTextView.setTextColor(mContext.getResources().getColor(R.color.meddark_gray));
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
similarArticleTextView.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
layoutParams.setMargins(ConversionHelper.dpToPx(5), 0, ConversionHelper.dpToPx(5), ConversionHelper.dpToPx(20));
similarArticleTextView.setText(similarArticle.title);
similarArticleTextView.setId((int) similarArticle.id);
similarArticlesLinearLayout.addView(similarArticleTextView);
similarArticleTextView.setClickable(true);
similarArticleTextView.setOnClickListener(relatedArticleClickListener);
similarArticleTextView.setLayoutParams(layoutParams);
}
}
I'm first setting the listener at the top:
private static OnClickListener relatedArticleClickListener;
And the function is:
//RELATED ARTICLE CLICK
relatedArticleClickListener = new OnClickListener()
{
public void onClick(View v) {
Log.d("MYLOG", "RL Article clicked " + v.getId());
Intent myIntent = new Intent(v.getContext(),MainActivity.class);
myIntent.putExtra("id", v.getId());
startActivity(myIntent);
finish();
}
};
Hi all in my application by using web service i get the data from database and stored that data in hash table.I took that data from hast table to array.this array data can be displayed in button.My array contains 10 elements.For animation i used view flipper.Now i want to do is display that array elements on button one after another for every 10sec.But in Updater method i didn't get all array elements.How to solve this one
i am sending my code
//in on create method i wore this one
user_advertise is the hash table
System.out.println(""+user_advertise.size());
array=new String[user_advertise.size()];
e= user_advertise.keys();
int i = 0;
int j=0;
for(i=user_advertise.size();;i++){
array[j]=e.nextElement().toString();
LinearLayout layout = (LinearLayout) findViewById(R.id.LinearLayout01);
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
Button buttonView = new Button(this);
buttonView.setText("" +array[i]);
Timer timing = new Timer();
timing.schedule(new Updater(buttonView), 3000, 3000);
ViewFlipper flipper = new ViewFlipper (this);
flipper.addView(buttonView);
layout.addView(flipper,p);
flipper.startFlipping();
flipper.setClickable(true);
flipper.setFlipInterval(10000);
flipper.setInAnimation(AnimationUtils.loadAnimation(this,R.anim.push_left_in));
flipper.setOutAnimation(AnimationUtils.loadAnimation(this,R.anim.push_left_out));
}
}catch(Exception e)
{
Log.v("Add",e.toString());
}
}
private class Updater extends TimerTask {
private final Button buttonView;
public Updater(Button buttonView) {
this.buttonView = buttonView;
}
public void run() {
buttonView.post(new Runnable() {
public void run() {
int k=0;
buttonView.setText(" ");
buttonView.setText(""+array[k].toString()+"");
if(array[++k]!= null)
{
k++;
}
}
You have defined and initialized int k=0; within the thread block so everytime it will run, k will always be 0 so you will have to define it outside.
Also
if(array[++k]!= null)
{
k++;
}
will increment k twice : one for the if test and one in the block
What you want is:
if(k != array.length - 1) k++;