Please see my code below. I am unable to make SetGravity work.
How come?
Layout Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="25dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:longClickable="true"
android:orientation="vertical" >
<EditText
android:id="#+id/etCommands"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Type a command"
android:password="true" />
<LinearLayout
android:weightSum="100"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_weight="20"
android:id="#+id/btnResults"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Results" />
<ToggleButton
android:paddingBottom="10dp"
android:layout_weight="80"
android:id="#+id/passTog"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="ToggleButton" android:checked="true"/>
</LinearLayout>
<TextView
android:id="#+id/tvResults"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="invalid" />
</LinearLayout>
java code:
public class TextPlay extends Activity {
private static final String TAG = "MyApp";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
Button chkCmd = (Button) findViewById(R.id.btnResults);
final ToggleButton passTog = (ToggleButton) findViewById(R.id.passTog);
final EditText input = (EditText) findViewById(R.id.etCommands);
final TextView display = (TextView) findViewById(R.id.tvResults);
passTog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (passTog.isChecked()) {
input.setInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_VARIATION_PASSWORD);
} else {
input.setInputType(InputType.TYPE_CLASS_TEXT);
}
}
});
chkCmd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String check = input.getText().toString();
Log.i(TAG, "Check Value is: " + check);
if (check.contentEquals("left")) {
Log.i(TAG, "I am under left ");
display.setGravity(Gravity.LEFT); //WHYW ILL YOU NOT WORK SETGRAVITY?????????????
} else if (check.contentEquals("center")) {
display.setGravity(Gravity.CENTER);
} else if (check.contentEquals("right")) {
display.setGravity(Gravity.RIGHT);
}
else if (check.contentEquals("blue")) {
display.setGravity(Gravity.RIGHT);
}
}
});
}
}
I just tested and it works.. You might be doing a few things wrong;
First of all, when you type "left" into the text field, are you making sure that you didn't type "Left" (most keyboards capitalize the first letter)
If you are sure about the above, do you see the log that says "I am under left " (Not the "Check is")? If not, then it's not getting there somehow..
If you are indeed seeing it, you might want to clean/build your project (in Eclipse Project-> Clean -it does cleaning and re-building)
If that doesn't work neither, you might want to change your target build (change it to API level 10 or so) You don't really need to worry about the target build if you are just using this as an exercise to learn.
I think we're not able to change UI this way.
I usually do like this.
TableLayout table1 = (TableLayout) findViewById(R.id.table1);
txtresult.setGravity(Gravity.RIGHT);
((TableLayout) table1).addView(txtresult);
It works with me.
So I suggest you to do a trick like delete that TextView "display" and generate a new one with new Gravity properties.
Hope it works!
Linh
Try to set layout_gravity="center" and layout_width="wrap_ontent" maybe that will do it :)
set layout_width="wrap_content" and set the layout gravity.
Have you tried to call invalidate after you change the layout attribute of your text view?
Android Documentation - View.invalidate()
Change the conditions as below:
check.equalsIgnoreCase("left")
Hope this solves ur problem.
View.invalidate() must be involved on UI thread. If you are doing the view re-configuration within a Listener callback which is your case, then you probably need call View.postInvalidate(), check out the API:
public void invalidate ()
Since: API Level 1
Invalidate the whole view. If the view is visible, onDraw(android.graphics.Canvas) will be called at some point in the future. This must be called from a UI thread. To call from a non-UI thread, call postInvalidate().
Try this:
<LinearLayout
android:id="#+id/llResults"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center">
<TextView
android:id="#+id/tvResults"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="invalid" />
</LinearLayout>
Instead of Doing :- tvResults.setGravity
try setting gravity of linearlayout :- llResults.setGravity
your code works good for me, i´ve tested on a real device with android 4.0.3 (Nexus S), the only thing that can be bothering you its capital letters as #Tolga E told.
you can try:
check.equalsIgnoreCase("left")
instead of:
check.contentEquals("left")
and debugging, put a breakpoint on the if´s to check that your code is actually trying to modify the gravity or its skipping that line.
Hope it helps.
If anyone who's following thenewboston's tutorial stumbles upon this with the same problem, it's an issue with the display variable. Just change
final TextView display = (TextView) findViewById(R.id.tvDisplay);
to
final TextView display = (TextView) findViewById(R.id.tvResults);
up with the other variable declarations.
I think setGravity method has been depreciated from API 4.0 . I don't see any alternative. Only way left you need to use API level 8.0. I am also getting nulpointer exceptions in log cat by using setGravity method
Set your TextView's width as android:layout_width="fill_parent"then you can set it programmatically using myTextView.setGravity(Gravity.CENTER) .
Related
First, I'll start by saying I've visited this two:
question 1 about this subject, question 2 about this subject
and both have failed me.
Second, my app is based on a single map fragment, i don't know if that's an issue, but the TextView is part of an info window which is displayed over the map.
I have the following TextView in xml:
<TextView
android:id="#+id/tv_link"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:linksClickable="true"
android:autoLink="web" />
which I want to make into a link, I'm feeding the text programatically, and can see the text as it is, but it is not clickable, or "hyper-link"ed.
The following is the part where I set up the TextView in my activity:
TextView tvLink = (TextView) v.findViewById(R.id.tv_link);
// make the link clickable
tvLink.setClickable(true);
tvLink.setMovementMethod(LinkMovementMethod.getInstance());
String text = (String) urls.get(arg0.getTitle());
// Setting the link url
tvLink.setText(Html.fromHtml(text));
I have also tried making the TextView have attribute of android:onClick="openBrowser" and have this class openBroweser:
public void openBrowser(View view){
//Get url from tag
String url = (String)view.getTag();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
//pass the url to intent data
intent.setData(Uri.parse(url));
startActivity(intent);
}
but it also didn't work. I might have made a mess while trying the different approached, but I did try to separate each try. and am confused and in need of an outside look.
EDIT 1 :
added the following:
My string in the res file (inside a string-array)
Click here for more info about this location
(which works here, so I assume it should be a legal link as needed)
My whole XML file as requested in comment
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_gravity="center_horizontal"
/>
<TextView
android:id="#+id/tv_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/tv_link"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp" />
</LinearLayout>
<ImageView
android:id="#+id/iv_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
/>
What you are trying to do will not work because a Google Maps InfoWindow is not a live view.
In the documentation for Custom Info Windows it states:
The info window that is drawn is not a live view. The view is rendered
as an image (using View.draw(Canvas)) at the time it is returned. This
means that any subsequent changes to the view will not be reflected by
the info window on the map. To update the info window later (for
example, after an image has loaded), call showInfoWindow().
Furthermore, the info window will not respect any of the interactivity
typical for a normal view such as touch or gesture events. However you
can listen to a generic click event on the whole info window as
described in the section below.
and
As a result, any listeners you set on the view are disregarded and you
cannot distinguish between click events on various parts of the view.
So the clicks on the individual tv_link TextView within the overall InfoWindow layout will not be processed.
You need to use the OnInfoWindowClickListener to listen for clicks on an InfoWindow
To begin with take out:
android:linksClickable="true"
android:autoLink="web"
Like this:
<TextView
android:id="#+id/tv_link"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"/>
This is working for me with a hard coded url. I suspect the way you are formatting your url is not correct.
String text = (String) urls.get(arg0.getTitle());
I'm not sure what you are getting from this, if you are using an array of strings.
The two questions you have linked to both use this format:
String text = "<a href='http://www.google.com'> Google </a>";
Link text
You need to format your string resources like this:
<string name="txtCredits">Google</string>
I cannot see how your custom class openBrowser is fetching the string in the right format for you.
I suggest you log everything.
String text = (String) urls.get(arg0.getTitle());
Log.i("url = ", text);
tvLink.setText(Html.fromHtml(text));
Use below which will do all your task
String str = holder.restContactInfoTV.getText().toString();
int index = str.lastIndexOf(",");
SpannableString snstr = new SpannableString(str);
ClickableSpan Span = new ClickableSpan() {
#Override
public void onClick(View textView) {
try {
String mobile = CUrrentOrderChild
.getRestaurantMobileCO();
Intent intent = new Intent(Intent.ACTION_CALL,
Uri.parse("tel:" + mobile));
startActivity(intent);
} catch (Exception e) {
}
}
#Override
public void updateDrawState(TextPaint ds) {
// TODO Auto-generated method stub
super.updateDrawState(ds);
// ds.setColor(Color.RED);
//ds.setUnderlineText(true);
}
};
snstr.setSpan(Span, index + 2, snstr.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
holder.restContactInfoTV.setText(snstr);
holder.restContactInfoTV.setMovementMethod(LinkMovementMethod.getInstance());
I am trying to clear the text in my edit text field but for some reason it is not working.
I have declared an edit text field in the xml of my view:
<EditText
android:id="#+id/enterGlucoseLevel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/mySimpleXYPlot"
android:layout_centerHorizontal="true"
android:ems="10"
android:inputType="numberDecimal" />
I have used the attribute onClick to link my button to the enterGlucoseAction() method in my MainActivity class:
<Button
android:id="#+id/enterGlucoseButton"
android:clickable="true"
android:onClick= "enterGlucoseAction"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/enterGlucoseLevel"
android:layout_centerHorizontal="true"
android:text="#string/enterGlucoseLvlButton" />
Here is that method:
public void enterGlucoseAction(View v) {
glucoseField.setText("");
Toast.makeText(v.getContext(), "You clicked the button", Toast.LENGTH_SHORT).show();
}
I get the toast pop up but my edit text field is not being cleared.
Here is my on create and instance variables in case the problem lies there.
private XYPlot plot;
private Button addGlucoseLevel;
private EditText glucoseField;
private XYSeries currentSeries;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addGlucoseLevel = (Button) findViewById(R.id.enterGlucoseButton);
glucoseField = (EditText) findViewById(R.id.enterGlucoseLevel);
currentSeries = new SimpleXYSeries(Arrays.asList(new Number[] { 7200, 8, 54000, 2, 64800, 4 }),
SimpleXYSeries.ArrayFormat.XY_VALS_INTERLEAVED,
"Glucose Level");
//Create an series of numbers to plot.
createGraph(currentSeries);
}
Thanks in advance.
And sorry, I know this has been asked before but I can't find a solution to my problem specifically.
To clear your EditText which accepts numbers use clear() method:
glucoseField.getText().clear();
You can try setting it this way:
((EditText)findViewById(R.id.enterGlucoseLevel)).getText().clear();
Alternatively you can use getText().clear(); just replace glucoseField.setText(""); with glucoseField.getText().clear();
You should use
setText("\b");
As we can use escape sequence
((EditText)findViewById(R.id.yourEditTextId)).getText().clear();
anything else crashed.
I wanted to display blinking cursor at the end of the text in TextView .
I tried by android:cursorVisible="true" in TextView But no go .
Even i tried text.setCursorVisible(true); Doesn't work .
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:cursorVisible="true"
android:textCursorDrawable="#null" />
Does any one know any solution for it ?
First of all you should use EditText in place of TextView for taking input. If still the cursor doesn't blink, set the android:cursorVisible="true"attribute in xml file, it should make the cursor blink. If your cursor is not visible in edit text, that's also a reason one can't see the cursor blinking. Set android:textCursorDrawable="#null". This should solve your problem
<EditText
android:id="#+id/editext1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textCursorDrawable="#null"
android:cursorVisible="true">
</EditText>
In your activity class, add this code as well.
EditText input = (EditText)findViewById(R.id.edittext1);
input.setSelection(input.getText().length());
There is a solution for this.
I had to do this when I was making a terminal app and I used a simple runnable put a cursor at the end and make it blink.
I made 3 class variables:
private boolean displayCursor;
private boolean cursorOn;
private String terminalText;
private TextView terminal; // The TextView Object
terminalText keeps track of the text to be displayed.
Created a class method that runs the runnable the first time
private void runCursorThread() {
Runnable runnable = new Runnable() {
public void run() {
if (displayCursor) {
if (cursorOn) {
terminal.setText(terminalText);
} else {
terminal.setText(terminalText + '_');
}
cursorOn = !cursorOn;
}
terminal.postDelayed(this, 400);
}
};
runnable.run();
}
And initiated the variables and called runCursorThread() in onCreate()
cursorOn = false;
displayCursor = true;
runCursorThread();
I think you should go for EditText. You can set its background and make it appears like TextView with below code.
Step 1
<EditText
android:id="#+id/edtText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent" >
</EditText>
Step 2
EditText edt = (EditText) findViewById(R.id.edtText);
edt.setSelection(edt.getText().length());
Output
Finally Fixed this Using the EditText as per #Chintan Rathod advice.
<EditText
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"/> //reference to #Chintan Rathod.
Code
EditText text=(EditText) findViewById(R.id.text);
text.setText("hello");
text.setSelection(text.getText().length()); // reference to #Umer Farooq code.
I would like to create a loop somewhere in my Android code that changes the color of a drawable rectangle between two colors continuously at some rate. I would like to start and stop its blinking using two buttons. I have done a lot of research, but just can't seem to figure out how to do it. I am new to android and do not have experience with run() methods. But I am guessing I have to make some kind of rectangle class with a run() method that will animate it into changing colors.
I am also fairly new to android, but I will give it a shot.
Since you say you want it to blink, you should be able to switch the actual image between, lets say, blue and red, with a simple 'for' loop. When the button is pressed, you could change the status of a boolean from false to true. Then, when the 'for' statement is not true anymore, it jumps to the next set of code, which stops it. Here is what I would do.
Your XML for the two buttons:
<Button
android:id="#+id/start"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Start"
android:Clickable="true"
android:onClick="start"
/>
<Button
android:id="#+id/stop" <!-- Gives the button an ID to use in java code -->
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Stop" <!-- sets the text on the button -->
android:Clickable="true" <!-- makes the button clickable -->
android:onClick="stop" <!-- The method it calls when it is clicked, removes the necessity of an OnClickListener -->
/>
Now, you would have 2 ImageViews: blue_rectangle and red_rectangle, both in the same place in the layout. Here is the XML for the two ImageViews
<ImageView
android:id="#+id/blue_rectangle"
android:layout_width="100dp"
android:layout_height="75dp"
android:layout_marginLeft="50dp"
android:layout_marginTop="5dp"
android:src="#drawable/blue_rectangle" />
<ImageView
android:id="#+id/red_rectangle"
android:layout_width="100dp"
android:layout_height="75dp"
android:layout_marginLeft="50dp"
android:layout_marginTop="5dp"
android:src="#drawable/red_rectangle" />
This next part is the tricky part.
Here is the Java.
package your.package.name.thingy.here;
//everything it tells you to import goes here
public class BlinkingActivity extends Activity{
ImageView blueRectangle;
ImageView redRectangle;
Button start;
Button stop;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourLayout);
blueRectangle = (ImageView) findViewById(R.id.blue_rectangle);
redRectangle = (ImageView) findViewById(R.id.red_rectangle);
start = (Button) findViewById(R.id.start);
stop = (Button) findViewById(R.id.stop);
Boolean isBlinking = new Boolean(false);
blinkRectangle(whateverVariableThisNeeds);
}
public static void blinkRectangle(View view){
blueRectangle.setVisibility(View.INVISIBLE);
redRectangle.setVisibility(View.INVISIBLE);
for(initialization; isBlinking; update){
blueRectangle.setVisibility(View.VISIBLE);
blueRectangle.postDelayed(new Runnable() {
#Override
public void run() {
blueRectangle.setVisibility(View.INVISIBLE);
}
}, 2000); //the 2000 is the number of milliseconds for how long blue is visible
redRectangle.setVisibility(View.VISIBLE);
redRectangle.postDelayed(new Runnable() {
#Override
public void run(){
redRectangle.setVisibility(View.INVISIBLE);
}
}, 2000);
blueRectangle.setVisibility(View.VISIBLE); //This prevents a bug where if the user hits the stop button at just the right time, both rectangles will be invisible.
}
public static void start(View view){ //no need to call this anywhere, the XML onClick does it for you
isBlinking = true; //I think this is how you set a boolean, if not, correct me.
}
public static void stop(View view){//same here
isBlinking = false; //again, correct me if I'm wrong.
}
}
Here is what the code basically does.
It has a boolean which is defaulted to false. While it is false, the rectangle does not blink. While it is true, the for statement in blinkRectangle() runs. That for loop makes the blue on visible, waits 2 seconds, makes it invisible, makes the red one visible, waits two seconds, and repeats. The start() and stop() methods switch the boolean to true and false, respectively. I think this type of for loop re-checks the boolean when it gets back to the top. I have never worked with it before. That's what I could gather from the website I looked at.
Well, I think that about does it. If you don't understand what any of the code does, or it doesn't work, or I have the question wrong, or I am just downright wrong, or ANYTHING, just comment on this answer. I hope this works!
Good Luck!
P.S. Here are the websites I used for reference
http://www.tutorialspoint.com/java/java_loop_control.htm
http://www.java-examples.com/java-boolean-example
Wow...I just realized this question is 2 years old. Still, I hope this helps you!
This question has been asked several times, but everyone gives the reason for why this occurs (i.e. calculation occurs before the layout is laid). But I need the solution for this. I tried getBottom();, getTop();, getLocationOnScreen(int[] location);. But all returns the value Zero (0). I even tried giving these in onStart();, to give time for layout to be laid, but no luck.
Here is my code:
TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.textView1);
Log.d("getBottom :", Integer.toString(tv.getBottom()));
Log.d("gettop :", Integer.toString(tv.getTop()));
int[] location = new int[2];
tv.getLocationOnScreen(location);
Log.d("getlocationonscreen values :", Integer.toString(location[0])+" "+Integer.toString(location[1]));
}
#Override
protected void onStart() {
Log.d("getBottom in onStart :", Integer.toString(tv.getBottom()));
Log.d("gettop in onStart :", Integer.toString(tv.getTop()));
int[] location = new int[2];
tv.getLocationOnScreen(location);
Log.d("getlocationonscreen in onStart :", Integer.toString(location[0])+" "+Integer.toString(location[1]));
super.onStart();
}
Layout XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="156dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
Again, I apologize for repeating the question. Thanks in advance.
You put the 'measuring' in the onWindowFocusChanged()-method.
As the documentation states:
This is the best indicator of whether this activity is visible to the user.
You could also put it in the onResume() which is the last step before the application is completely on screen and active, however:
Keep in mind that onResume is not the best indicator that your activity is visible to the user; a system window such as the keyguard may be in front. Use onWindowFocusChanged(boolean) to know for certain that your activity is visible to the user (for example, to resume a game).
If the window/view has not yet been displayed there is no guarantee that it has its measurements, thus the previous method would be better.