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");
}
});
Related
I don't understand why it isn't just as simple as this...
// Add field
val LineLayoutInfo = findViewById<View>(R.id.LineLayoutInfo) as LinearLayout
val Add_Field = findViewById<View>(R.id.buttonAddField) as Button
Add_Field.setOnClickListener{
val tv1 = TextView(this#MainActivity)
tv1.text = "Show Up"
val t = TextView(applicationContext)
LineLayoutInfo.addView(tv1)
}
All I want to do is create a new TextView inside my current LinearLayout. This part of the code is written in Kotlin and stored in the OnCreate(). Is it maybe because I need to refresh the activity?
The output I get when I push the button, looks like this.
D/HwAppInnerBoostImpl: asyncReportData com.xxx.httpposter,2,1,1,0 interval=83
I/ViewRootImpl: jank_removeInvalidNode all the node in jank list is out of time
V/AudioManager: playSoundEffect effectType: 0
V/AudioManager: querySoundEffectsEnabled...
D/HwAppInnerBoostImpl: asyncReportData com.xxx.httpposter,2,1,2,0 interval=353
You can try something like this
private LinearLayout mLayout;
private Button mButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mLayout = (LinearLayout) findViewById(R.id.linearLayout);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(onClick());
TextView textView = new TextView(this);
textView.setText("New text");
}
private OnClickListener onClick() {
return new OnClickListener() {
#Override
public void onClick(View v) {
mLayout.addView(createNewTextView("New Text"));
}
};
}
private TextView createNewTextView(String text) {
final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(this);
textView.setLayoutParams(lparams);
textView.setText("New text: " + text);
return textView;
}
Here, you could just create the TextView and set it's Visibility to INVISIBLE on MainActivity after the onCreate() of the program, then on button click set it to VISIBLE. You could do this infinitely!
I want to put elements in my view depending on the position of the other ones. Let me explain : First, I have two textviews and I've put successfully the second (villeOffre) one under the first one (titreOffre) :
titreOffre = (TextView) findViewById(R.id.offreTitre);
titreOffre.setText(capitalizedString(offre.getTitle()));
villeOffre = (TextView) findViewById(R.id.offreVille);
villeOffre.setText(offre.getLocality());
infos = (TextView) findViewById(R.id.infos);
ViewTreeObserver vto = titreOffre.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener(
{
#Override
public void onGlobalLayout()
{
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) villeOffre.getLayoutParams();
params.setMargins(15,titreOffre.getBottom()+12,15,0);
villeOffre.setLayoutParams(params);
titreOffre.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
This works perfectly, but now I want to put a third textview (infos) which is depending on villeOffre position. How to do that ?
Thanks a lot.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rr = new RelativeLayout(this);
b1 = new Button(this);
b1.setId(R.id.Button01);
recent = b1;
b1.setText("Click me");
rr.addView(b1);
setContentView(rr);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tv1 = new TextView(can.this);
tv1.setId((int)System.currentTimeMillis());
lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.BELOW, recent.getId());
tv1.setText("Time: "+System.currentTimeMillis());
rr.addView(tv1, lp);
recent = tv1;
}
});
}
I am trying to add a textview inside a tab dynamically. using this code
Oncreate()
{
OA.loaderShow(this); //Loader display
new Thread(new Runnable(){
public void run()
{
Looper.prepare();
fetchDocs();
OA.loaderHide(); //Loader Hide
Looper.loop();
}
}).start();
}
fetchDocs()
{
LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
TextView text = new TextView(this);
text.setText(mytext);
layout.addView(text);
}
I am getting this error "Only the original thread that created a view hierarchy can touch its view".
Please Help.
Put above inside the following block
runOnUiThread(new Runnable() {#Overridepublic void run() {//your code here}}
Try using a handler like this:
EDIT:
protected static final int SET_TEXTVIEW = 0;
Oncreate()
{
OA.loaderShow(this); //Loader display
new Thread(new Runnable(){
public void run()
{
Looper.prepare();
handler.sendMessage(handler.obtainMessage(SET_TEXTVIEW));
OA.loaderHide(); //Loader Hide
Looper.loop();
}
}).start();
}
public Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SET_TEXTVIEW :
LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
TextView text = new TextView(this);
text.setText(mytext);
layout.addView(text);
}
}
};
Add this in the onCreate method rather than adding from else where.
Hi I'm kind of beginner to android OS programming, and I got stuck with a problem, I cant figure out how to do a dynamic background, based on timers (say each 10 seconds a background changes to a different one) I have some code but it comes up with error, here's a sample:
private static final long GET_DATA_INTERVAL = 10000;
int images[] = {R.drawable.smothie1,R.drawable.omletherb1};
int index = 0;
ImageView img;
Handler hand = new Handler();
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
LinearLayout layout= (LinearLayout)findViewById(R.id.LinearView1);
hand.postDelayed(run, GET_DATA_INTERVAL);
}
Runnable run = new Runnable() {
public void run() {
layout.setBackgroundResource(LinearView1).getDrawable(images[index++]);
if (index == images.length)
index = 0;
hand.postDelayed(run, GET_DATA_INTERVAL);
Any help would be greatly apprieciated :D thanks
EDIT: The errors I get are on this line:
layout.setBackgroundResource(LinearView1).getDrawable(images[index++]);
It says that:
-layout cannot be resolved
-the method getDrawable(int) is undefined for the type Object
This error:
layout.setBackgroundResource(LinearView1).getDrawable(images[index++]);
It says that:
-layout cannot be resolved
-the method getDrawable(int) is undefined for the type Object
Please help :)
I have finally worked it out, after removing a few errors I have came up with this (and its working) :
public class CookBookActivity extends Activity {
/** Called when the activity is first created. */
private static final long GET_DATA_INTERVAL = 1000;
int images[] = {R.drawable.omletherb1,R.drawable.smothie1};
int index = 0;
LinearLayout img;
Handler hand = new Handler();
private LinearLayout layout;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
layout = (LinearLayout)findViewById(R.layout.main);
hand.postDelayed(run, GET_DATA_INTERVAL);
Typeface tf2 = Typeface.createFromAsset(getAssets(),
"fonts/BPreplay.otf");
TextView tv2 = (TextView) findViewById(R.id.textView2);
tv2.setTypeface(tf2);
Typeface tf = Typeface.createFromAsset(getAssets(),
"fonts/BPreplay.otf");
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setTypeface(tf);
Button mainNext = (Button) findViewById(R.id.nextScreen1);
mainNext.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent();
i.setClassName("com.unKnown.cookbook", "com.unKnown.cookbook.screen1");
startActivity(i);
}
});
}
Runnable run = new Runnable() {
public void run() {
layout.setBackgroundDrawable(getDrawable(index++));
if (index == images.length)
index = 0;
hand.postDelayed(run, GET_DATA_INTERVAL);
}
};
protected Drawable getDrawable(int i) {
// TODO Auto-generated method stub
return getResources().getDrawable(images[i%2]);
}
}
I am trying to make a simple application where every so many seconds the text being displayed is changed to another, the input is given by the user before the onClick and set to different strings. I can't find a way to have the different strings displayed at different times - and is it even possible to use one single textView to display different text at different times, never at the same time....
Any help is appreciated. Thanks.
Andrew
This is my code so far...
public class ThunderActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//when the game button is pressed
final Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Enter names
//player one
final EditText player1 = (EditText) findViewById(R.id.editText1);
final String player = player1.getText().toString().trim();
//player 2
final EditText player2 = (EditText) findViewById(R.id.editText2);
final String player11 = player2.getText().toString().trim();
//player 3
final EditText player3 = (EditText) findViewById(R.id.editText3);
final String player111 = player3.getText().toString().trim();
//switches to second screen - the play xml file
setContentView(R.layout.main2);
//starts the song
MediaPlayer mp = MediaPlayer.create(getBaseContext(), R.drawable.thunderstruck);
mp.start();
//shuffle names and display them
//displays name - testing purposes
v = (TextView) findViewById(R.id.textView1);
String text = player;
((TextView) v).setText(text);
//v = (TextView) findViewById(R.id.textView2);
//String text2 = player11;
//((TextView) v).setText(text2);
}
});
}
}
An easier way to do the same thing is using the Handler.postDelayed method.
public class Act extends Activity{
private Handler handler = new Handler();
private TextView view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Initialize view
handler.postDelayed(new ViewUpdater("str1", view), 10000);
handler.postDelayed(new ViewUpdater("str2", view), 20000);
handler.postDelayed(new ViewUpdater("str2", view), 30000);
}
private class ViewUpdater implements Runnable{
private String mString;
private TextView mView;
public ViewUpdater(String string, TextView view){
mString = string;
mView = view;
}
#Override
public void run() {
mView.setText(mString);
}
}
}
Something like that: You get the basic idea!
ok here is your hint:
Say your TextView is called yourTextView
String[] texts = new String[]{"String1","String2","String3"}; //etc
Runnable myRun = new Runnable(){
public void run(){
for(int i=0;i<texts.length;i++){
synchronized(this){
wait(30000); //wait 30 seconds before changing text
}
//to change the textView you must run code on UI Thread so:
runOnUiThread(new Runnable(){
public void run(){
yourTextView.setText(texts[i]);
}
});
}
}
};
Thread T = new Thread(myRun);
T.start();
A more correct answer would be to use a ViewFlipper. You can add all your TextViews to it and call startFlipping(). You can set the flip interval by calling setFlipInterval(int milliseconds).