change pic in dynamic UIandroid - android

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);

Related

Add row dynamically to android table after 1 minute

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);
}

How to update linearlayout child view programmatically in android?

I have created linearylayout programatically. where it has multiple rows created having white background. Now if I click on any row then only that row's imageview icon should be changed(should be green) and other row's imageview background should be changed to white. Is there any substitude of notifyDataSetChanged for linearlayout in android. below is my code.
for (int i = 0; i <= obj_tribe_info.al_ethnicity_secondary.size(); i++) {
final int position = i;
al_eth_bool.add(false);
final LinearLayout ll_values = new LinearLayout(_activity);
ll_values.setOrientation(LinearLayout.HORIZONTAL);
ll_values.setGravity(Gravity.CENTER_VERTICAL);
LayoutParams LLParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
ll_values.setLayoutParams(LLParams);
ll_values.setBackgroundResource(R.drawable.my_tribe_box_top);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(50, 0, 0, 0);
final ImageView iv_icon = new ImageView(_activity);
if (al_eth_bool.get(position)) {
iv_icon.setBackgroundResource(R.drawable.notify_onn);
} else {
iv_icon.setBackgroundResource(R.drawable.notify_off);
}
iv_icon.setLayoutParams(layoutParams);
ll_values.addView(iv_icon);
TextView tv_value = new TextView(_activity);
tv_value.setTextColor(_activity.getResources().getColor(
R.color.black));
tv_value.setLayoutParams(layoutParams);
if (i == 0) {
tv_value.setText(obj_tribe_info.str_ethnicity_primary);
} else {
tv_value.setText(obj_tribe_info.al_ethnicity_secondary
.get(i - 1).str_ethnicity_secondary);
}
ll_values.addView(tv_value);
ll_ethnicity.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
ll_ethnicity.addView(ll_values);
}
});
ll_values.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (al_eth_bool.get(position)) {
iv_icon.setBackgroundResource(R.drawable.notify_off);
al_eth_bool.set(position, false);
} else {
iv_icon.setBackgroundResource(R.drawable.notify_onn);
al_eth_bool.set(position, true);
}
}
});
}
No, there is no substitute for notifyDataSetChanged(), you have to manually inform your ImageViews of that change.
You could iterate like this, as soon as you have a change:
for(int i= 0; i < ll_ethnicity.getChildCount(); i++){
ImageView iv = (ImageView) ((ViewGroup)ll_ethnicity.getChildAt(i)).getChildAt(0);
// new background because something has changed
// check if it's not the imageView you just clicked because you don't want to change its background
iv.setBackground(...);
}
For better performance you may also create an HashMap with your ImageViews and later access it to change some of them as you see fit.
I believe what you're looking for is View.invalidate() method. It tells the application that this view is no longer correct, and it will be redrawn when possible. Call this at the end of the onClick method.

Issues Using Android LinearLayout

I have a LinearLayout, containing one EditText and one TextView. My ConsoleWindow is running in a loop, and I would like to update the TextView in each Iteration.
The problem is that I may initialize the EditText only once (otherwise it is inaccessible) and also the LinearLayout may only be initialized once (otherwise it would remove the EditText).
I cannot put the LinearLayout and the EditText in an if-statement:
if (firstRun) {
// initialize LinearLayout and EditText
firstRun = false;
}
// TEXTVIEW
TextView tv = new TextView(getApplicationContext())
tv.setText(dataStringTot);
layout.addView(tv); // "Qualifier must be an Expression."
because the IDE Returns at layout.addView(tv); : "Qualifier must be an expression."
My Code:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getInetContent();
}
getInetContent() { // would be a thread
// getting data...
Bundle b = new Bundle();
b.putString("StringNMEA", NMEA);
Message m = mhandler.obtainMessage();
m.setData(b);
mhandler.sendMessage(m);
}
Handler handler = new Handler() {
public void handleMessage(Message msg) {
String dataString = "";
Bundle bundle = msg.getData();
if (bundle.containsKey("display")) {
ConsoleWindow(dataString);
}
}
}
private void ConsoleWindow(String dataString) {
// LINEAR LAYOUT
LinearLayout layout = new LinearLayout(this);
setContentView(layout);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setBackgroundColor(Color.parseColor("#000000")); // black
// EDITTEXT
EditText et = new EditText(getApplicationContext());
et.setHint("Enter Command");
layout.addView(et);
// TEXTVIEW
TextView tv = new TextView(getApplicationContext());
tv.setText(dataStringTot);
layout.addView(tv);
}
}
My Code with if-statement:
public boolean firstRun = true;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getInetContent();
}
getInetContent() { // would be a thread
// getting data...
Bundle b = new Bundle();
b.putString("StringNMEA", NMEA);
Message m = mhandler.obtainMessage();
m.setData(b);
mhandler.sendMessage(m);
}
Handler handler = new Handler() {
public void handleMessage(Message msg) {
String dataString = "";
Bundle bundle = msg.getData();
if (bundle.containsKey("display")) {
ConsoleWindow(dataString);
}
}
}
private void ConsoleWindow(String dataString) {
if (firstRun) {
// initialize LinearLayout and EditText:
// LINEAR LAYOUT
LinearLayout layout = new LinearLayout(this);
setContentView(layout);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setBackgroundColor(Color.parseColor("#000000")); // black
// EDITTEXT
EditText et = new EditText(getApplicationContext());
et.setHint("Enter Command");
layout.addView(et);
firstRun = false;
}
// TEXTVIEW
TextView tv = new TextView(getApplicationContext());
tv.setText(dataStringTot);
layout.addView(tv);
}
}
How could I fix this Problem?
I imagine you want to update the colours/text of them each iteration.
You don't need to create a new View each time you want to modify it. Set up your layout, get the views and then pass those views into your loop.
LinearLayout layout = new LinearLayout(this);
EditText et = new EditText(this);
TextView tv = new TextView(this);
layout.addView(et);
layout.addView(tv);
setContentView(layout);
et.setHint("Enter Command");
tv.setText(dataStringTot);
startLoop(et, tv);
public void startLoop(final EditText et, final TextView tv) {
...
}
If your loop is a thread of some sort that isn't run on the main thread you might need to wrap it in a run on ui thread.
runOnUiThread(new Runnable()
{
public void run()
{
Log.v("mainActivity", "test");
}
});

make a single button width to fill parent programmatically

How do I make a single button width to fill parent programmatically? I have done this but it cannot seem to work it is still located on top left with width just wrapping the content... here is some of the code on the button creation...
public class TEST_GIFDisplay extends Activity implements View.OnClickListener {
SurfaceView sview;
GifRun gr = new GifRun();
Button btnBack;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sview = new SurfaceView(this);
sview.setZOrderOnTop(true);
gr.LoadGiff(sview, this, R.drawable.smiley);
LinearLayout linearLayout1 = new LinearLayout(this);
linearLayout1.setOrientation(LinearLayout.VERTICAL);
linearLayout1.setBackgroundColor(Color.parseColor("#27ae60"));
linearLayout1.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
LinearLayout linearLayout2 = new LinearLayout(this);
linearLayout2.setOrientation(LinearLayout.VERTICAL);
linearLayout2.setBackgroundColor(Color.parseColor("#27ae60"));
linearLayout2.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
LinearLayout.LayoutParams p = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
p.weight = 1.0f;
btnBack = new Button (this);
btnBack.setText("Back");
btnBack.setBackgroundColor(Color.parseColor("#f1c40f"));
btnBack.setGravity(Gravity.CENTER_HORIZONTAL);
btnBack.setLayoutParams(p);
btnBack.setOnClickListener(this);
linearLayout2.addView(btnBack);
linearLayout1.addView(linearLayout2);
linearLayout1.addView(sview);
setContentView(linearLayout1);
}
#Override
public void onClick(View view) {
btnBack = (Button) view;
btnBack.setBackgroundColor(Color.parseColor("#2980b9")); //color change
new CountDownTimer(100, 50) {
#Override
public void onTick(long arg0) {
// TODO Auto-generated method stub
}
#Override
public void onFinish() {
btnBack.setBackgroundColor(Color.parseColor("#f1c40f")); // original color
}
}.start();//end color changed
finish();
}
}
You are adding the Button to linearLayout2. You should change the linearLayout2's width to MATCH_PARENT
linearLayout2.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
I hope this helps.
P.S: You can create Button's selectors for pressed and selected states, instead of using timer to show a pressed button effect. Here is a basic link that can help you in achieving this : android button selector

Programmatically create ImageView in Android

I followed this to create a simple animation.
The example creates manually an ImageView in the main layout, having a resource like this android:src="#anim/anim_android
The problem is, when I make a dynamic ImageView, and I set the resource like this myImageView.setImageResource(R.anim.anim_android);, the animation doesn't work, just views the first image of the sequence.
Any help?
Thanks.
you sould start the animation from you imageView :
myImageView.setImageResource(R.anim.anim_android);
final AnimationDrawable myAnimationDrawable = (AnimationDrawable)myImageViewn.getDrawable();
myImageView.post(
new Runnable(){
#Override
public void run() {
myAnimationDrawable.start();
}
});
}
EDIT : i think you didn't add the ImageView to your Layout ( contentView of your Activity ) ; try this :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RelativeLayout rootLayout = new RelativeLayout(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
rootLayout.setLayoutParams(params);
ImageView myAnimation = new ImageView(this);
RelativeLayout.LayoutParams paramsImage = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
paramsImage.addRule(RelativeLayout.CENTER_IN_PARENT);
myAnimation.setLayoutParams(paramsImage);
myAnimation.setImageDrawable(getResources().getDrawable(R.anim.anim_android));
rootLayout.addView(myAnimation);
setContentView(rootLayout);
final AnimationDrawable myAnimationDrawable = (AnimationDrawable)myAnimation.getDrawable();
myAnimation.post(new Runnable() {
#Override
public void run() {
myAnimationDrawable.start();
}
});
}

Categories

Resources