Android ScrollView height not changing - android

I have a layout with the following XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ScrollView
android:id="#+id/myScrollview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true" >
<LinearLayout
android:id="#+id/myEditLinearLayout"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content">
<EditText
android:id="#+id/myEdit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="8dip"
android:paddingRight="8dip"
android:maxLines="300"
android:scrollHorizontally="false"
android:hint="Type notes here..."
android:inputType="textNoSuggestions|textMultiLine"
android:layout_gravity="center_horizontal|center_vertical"
android:gravity="left"
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
</LinearLayout>
</ScrollView>
<RelativeLayout
android:id="#+id/layoutKbd"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<android.inputmethodservice.KeyboardView
android:id="#+id/myKeyboardView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:focusable="true"
android:focusableInTouchMode="true"
android:keyPreviewLayout ="#layout/kbdpreview"
android:visibility="gone" />
</RelativeLayout>
</RelativeLayout>
The top view is RelativeLayout with a ScrollView for the main content (which contains an EditText) and custom keyboard view. The custom keyboard pops up when the user clicks on the EditText.
It works perfectly for most part, but if the text being entered in the EditText is large, it gets covered by the custom keyboard view. So at that time, I need to adjust the ScrollView's height. I did it in the following manner:
// Activity's onCreate implementation
public void onCreate(Bundle savedInstanceState)
{
...
EditText editText = (EditText) findViewById(R.id.myEditLinearLayout);
editText.addTextChangedListener(m_tw);
...
}
private TextWatcher m_tw = new TextWatcher()
{
#Override
public void afterTextChanged(Editable s)
{
// This function returns if the custom keyboard is visible
if (m_customKeyboard.isCustomKeyboardVisible())
{
int kbdHeight = m_customKeyboard.mKeyboardView.getHeight();
int editTextBottom = m_editText.getBottom();
ScrollView scrollView = (ScrollView) findViewById(R.id.myScrollview);
Rect scrollBounds = new Rect();
Log.d(TAG, "Setting scrollview height = " + (editTextBottom + kbdHeight + 20));
scrollView.getHitRect(scrollBounds);
Log.d(TAG, "Old scroll bounds: left = " + scrollBounds.left + " right = " + scrollBounds.right + " top = " + scrollBounds.top + " bottom = " + scrollBounds.bottom);
scrollView.getLayoutParams().height = editTextBottom + kbdHeight + 20;
Log.d(TAG, "Setting scrollview height = " + (editTextBottom + kbdHeight + 20));
scrollView.getHitRect(scrollBounds);
Log.d(TAG, "New scroll bounds: left = " + scrollBounds.left + " right = " + scrollBounds.right + " top = " + scrollBounds.top + " bottom = " + scrollBounds.bottom);
}
}
};
The above does not work. It shows the same value for scrollBounds.bottom, before and after setting scrollView height.
What am I missing?

Put the property
android:layout_above="#+id/yourKeyboardLayout"
in your scrollview.

You could try putting android:windowSoftInputMode="adjustPan" in your manifest. If you don't like the result, perhaps you can use some other pan.

Add this
android:windowSoftInputMode="adjustPan"
in your manifest where activity is declare and you can also add in scroll view

If you want to change scrollview's LayoutParams, you should use the following code in you example:
ViewGroup.LayoutParams lp = scrollView.getLayoutParams();
lp.height = editTextBottom + kbdHeight + 20;
scrollview.setLayoutParams(lp);

Related

How to set text color for particular word in a sentence?

This is my response :
Upto 1Feet $2
After 3Feet $0.025
In this above response, I need to set green color for $2 and $0.025. Other text contains black color.
This is my xml Code,
<android.support.v7.widget.CardView
android:id="#+id/book_cardview_estimate_layout_driver"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/book_cardview_area_layout"
android:layout_centerHorizontal="true"
android:layout_marginLeft="13dp"
android:layout_marginRight="13dp"
android:layout_marginTop="30dp"
android:background="#ffffff"
android:visibility="visible"
card_view:cardElevation="8dp">
<RelativeLayout
android:id="#+id/estimate_layout_driver"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
android:visibility="visible">
<com.mylibrary.widgets.CustomTextView
android:id="#+id/estimate_driver_text_upto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="15dp"
android:layout_marginBottom="13dp"
android:text="Upto "
android:textColor="#000000"
android:textSize="15dp" />
<com.mylibrary.widgets.CustomTextView
android:id="#+id/estimate_driver_text_after"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/estimate_driver_text_upto"
android:layout_marginLeft="10dp"
android:layout_marginTop="13dp"
android:layout_marginBottom="15dp"
android:text="After"
android:visibility="visible"
android:textColor="#000000"
android:textSize="15dp" />
</RelativeLayout>
</android.support.v7.widget.CardView>
Here is java Code,
Tv_estimate_driver_text_upto.setText(getResources().getString(R.string.upto) + " " + min_feet + getResources().getString(R.string.feet) + " " + sCurrencySymbol + min_fare);
Tv_estimate_driver_text_after.setText(getResources().getString(R.string.after) + " " + after_per_feet + getResources().getString(R.string.feet) + " " + sCurrencySymbol + after_per_multi);
Explanation :
getResources().getString(R.string.upto) = upto text,
min_feet = 1 (its comes from json response),
getResources().getString(R.string.feet) = feet,
sCurrencySymbol = $ (this comes from json response),
min_fare = 2 (some amount , comes from json response)
Using Spans you can change style of part of Sentence.
Example :
// text1 for different color
text1 = "Upto 1Feet $";
// text 2 in different color
String text2 = min_fare;
span1 = new SpannableString(text1);
// optional if you want to change text size
span1.setSpan(new AbsoluteSizeSpan(textSize1), 0, text1.length(), SPAN_INCLUSIVE_INCLUSIVE);
// code for changing color of string 1
span1.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, R.color.colorPrimary)), 0,
text1.length(), 0);
// do same for string two and concat both span
CharSequence finalText = TextUtils.concat(span1, span2);
txtEventType.setText(finalText);
EDIT
void setSpan (Object what,
int start,
int end,
int flags)
Object what : What to apply ForegroundColorSpan / AbsoluteSizeSpan , start : start of string,end : end of string , flags : Flag of Spanned
Make your String as Html such as
<b><font color=#FF0000>$2</font></b> and setText with Html.fromHtml()
such as
textview.setText(Html.fromHtml(getResources().getString(R.string.upto) + " " + min_feet +
getResources().getString(R.string.feet) +
" <font color=#00FF00>" + sCurrencySymbol + min_fare + "</font></b>"));

ObjectAnimator, Changing "ScaleX" or "Left," but text doesn't stay properly centered

I need to animate three elements to show additional info when the user clicks on a button. I have a label (TextView tvAvailableToPair) that slides out from under a button (Button bSearchForDevices)--both of which start with a width of fill_parent--while it simultaneously slides up. I have it changing perfectly, but it isn't animated: I've achieved that via SetLayoutParams:
bSearchForDevices.setText(R.string.bSearchForDevicesDiscoveryStartedText);
FrameLayout.LayoutParams lp_bSFD =
(FrameLayout.LayoutParams) bSearchForDevices.getLayoutParams();
int mWidthOfBSearchForDevices = lp_bSFD.width =
(int) Math.round(fMeasureScreenWidth * 0.4);
int mLeftMarginOfBSearchForDevices = lp_bSFD.leftMargin =
Math.round(fMeasureScreenWidth - (fHorizontalMargin + lp_bSFD.width));
bSearchForDevices.setLayoutParams(lp_bSFD);
lp_bSFD = (FrameLayout.LayoutParams) tvAvailableToPair.getLayoutParams();
lp_bSFD.width = mLeftMarginOfBSearchForDevices;
lp_bSFD.leftMargin = 0;
tvAvailableToPair.setLayoutParams(lp_bSFD);
ViewGroup.LayoutParams lp = llAvailableToPair.getLayoutParams();
lp.height = Math.round(getResources().getDimensionPixelSize(
R.dimen.llAvailableToPair_height_expanded) * MainActivity.displayMetrics.density);
I learned a FrameLayout allows you to place elements on different Z-axis values (on top of or below another element; to cover or be covered over by another element). Here's my xml for this activity:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity"
android:id="#+id/rlDeviceListLayout"
android:background="#android:color/holo_blue_dark"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:fitsSystemWindows="true"
android:animateLayoutChanges="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior" >
<android.support.design.widget.AppBarLayout
android:id="#+id/ablToolbarLayout"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_alignParentTop="true"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<LinearLayout>
<!-- Existing devices for user to select -->
</LinearLayout>
<!-- This is what needs to be animated up once user presses the button -->
<LinearLayout
android:id="#+id/llAvailableToPairLayout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="#dimen/llAvailableToPair_height_collapsed"
android:layout_alignParentBottom="true"
android:paddingTop="4dp">
<!-- This Layout is used to stack the button over the textview -->
<FrameLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="56dp"
android:layout_marginBottom="4dp">
<!-- We'll change the width of this programmatically so that it appears to
elegantly slide to the left -->
<TextView
android:id="#+id/tvAvailableToPair"
android:text="#string/tvAvailableToPair"
android:layout_width="fill_parent"
android:layout_height="#dimen/bSearchForDevices_height"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:inputType="none"
android:gravity="center"
android:foregroundGravity="left"
android:textSize="16sp"
android:textColor="#ffffff" />
<!-- We'll change the text, width and left of this so that it reveals the
textview under it. It needs to appear as if it were elegantly squeezed
toward the right -->
<Button
android:id="#+id/bSearchForDevices"
android:text="#string/bSearchForDevicesPreliminaryText"
android:layout_width="fill_parent"
android:layout_height="#dimen/bSearchForDevices_height"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_marginRight="#dimen/activity_horizontal_margin"
android:foregroundGravity="right"
android:visibility="visible"
android:theme="#style/Base.ThemeOverlay.AppCompat.Dark"
android:gravity="center" />
</FrameLayout>
<ListView
android:id="#+id/lvAvailableToPair"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:visibility="visible" />
</LinearLayout>
</RelativeLayout>
Its the last three elements I'm changing. Using SetLayoutParams keeps the text centered (and I shorten the text on the button to allow for smaller screens and the label -- I'll need to animate that as well next, possibly using TextSwitcher Animate Text Using TextSwitcher In Android) after the change. Moving on to getting those changes to animate, I had to use a different approach:
bSearchForDevices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FrameLayout.LayoutParams lpTVATP = (FrameLayout.LayoutParams) tvAvailableToPair.getLayoutParams();
Paint paint = new Paint();
AnimatorSet RevealAvailableDevices = new AnimatorSet();
float fMeasuretvAvailableToPairTextWidth = paint.measureText(tvAvailableToPair.getText().toString()); // Function returns dp, not pixels
float fMeasurebSearchForDevicesTextWidth = paint.measureText(bSearchForDevices.getText().toString());
float fMeasureScreenWidth = MainActivity.displayMetrics.widthPixels; // + 0.5f; // Extra 0.5 to simplify/speed up rounding w/o a lot of excess code (LoungeKatt, via https://stackoverflow.com/questions/1016896/get-screen-dimensions-in-pixels) and used on Google's Android docs for just this purpose # https://developer.android.com/guide/practices/screens_support.html#dips-pels
float fHorizontalMargin;
// If the screen is cramped, we'll shorten the margins:
if (fMeasuretvAvailableToPairTextWidth > (fMeasureScreenWidth * 0.5)) {
fHorizontalMargin = (getResources().getDimension(R.dimen.activity_horizontal_margin_compressed) / MainActivity.displayMetrics.density);
} else {
fHorizontalMargin = (getResources().getDimension(R.dimen.activity_horizontal_margin) / MainActivity.displayMetrics.density);
}
/* This works PERFECTLY, but isn't animated:
bSearchForDevices.setText(R.string.bSearchForDevicesDiscoveryStartedText);
FrameLayout.LayoutParams lp_bSFD = (FrameLayout.LayoutParams) bSearchForDevices.getLayoutParams();
int mWidthOfBSearchForDevices = lp_bSFD.width = (int) Math.round(fMeasureScreenWidth * 0.4);
int mLeftMarginOfBSearchForDevices = lp_bSFD.leftMargin = Math.round(fMeasureScreenWidth - (fHorizontalMargin + lp_bSFD.width));
bSearchForDevices.setLayoutParams(lp_bSFD);
lp_bSFD = (FrameLayout.LayoutParams) tvAvailableToPair.getLayoutParams();
lp_bSFD.width = mLeftMarginOfBSearchForDevices;
lp_bSFD.leftMargin = 0;
tvAvailableToPair.setLayoutParams(lp_bSFD);
ViewGroup.LayoutParams lp = llAvailableToPair.getLayoutParams();
lp.height = Math.round(getResources().getDimensionPixelSize(R.dimen.llAvailableToPair_height_expanded) * MainActivity.displayMetrics.density);
*/
float fWidthOfbSearchForDevices = (float) ((fMeasureScreenWidth * 0.4));
float fWidthOftvATP = (fMeasureScreenWidth - ((fWidthOfbSearchForDevices * 1) + (fHorizontalMargin * 2)));
float fXOfbSearchForDevices = (fMeasureScreenWidth - (fWidthOfbSearchForDevices + (1 * fHorizontalMargin)));
Log.d(TAG, "...\nfMeasureScreenWidth = " + fMeasureScreenWidth + "\nfWidthOfbSearchForDevices = " + fWidthOfbSearchForDevices + "\nfHorizontalMargin = " + fHorizontalMargin +
"\nbSearchForDevices.getX() = " + bSearchForDevices.getX() + "\n (fXOfbSearchForDevices) X is going to be " + fXOfbSearchForDevices);
ObjectAnimator aniButtonMove = ObjectAnimator.ofInt(bSearchForDevices, "Left", (int) fXOfbSearchForDevices);
bSearchForDevices.setPivotX(fXOfbSearchForDevices + (fWidthOfbSearchForDevices / 2)); // No effect: To be in the center of where the button will end up at.
ObjectAnimator aniTextViewResize = ObjectAnimator.ofInt(tvAvailableToPair, "Right", (int) fXOfbSearchForDevices);
Log.d(TAG, "tvAvailableToPair's width = " + tvAvailableToPair.getWidth() + " tvAvailableToPair is supposed to be " + fWidthOftvATP + "\nWidth of bSearchForDevices = " + bSearchForDevices.getWidth());
RevealAvailableDevices.play(aniTextViewResize).with(aniButtonMove);
RevealAvailableDevices.start();
This produces an animation that correctly moves the bounds of the textview and button, but doesn't center the text to the new bounds (edges/left and right coordinates) of those elements: my button now shows a lot of leading empty space just before it shows S, E and half of A of "Search For Devices;" in other words, it's clipped. I need it kept centered (as is when using SetLayoutParams). The same applies to the textview: the last 5 letters of "Available Devices" get clipped off.
Is there a better way to create this animation that has three elements changing shape (and preferably changing the button's text as well)? I've tried ScaleX but am unable to get it to sync correctly as it pivots at the center without sliding to the right side, nor the textview to slide while it shrinks...maybe ScaleX but change the pivot to the left edge... Or maybe a PropertyValuesHolder?
3/15/2016 Update:
Here's what I've got: https://www.dropbox.com/s/n14hed6xcknfh9b/SS_20160315_135938.mp4?dl=0
And what I need it to look like post animation

How to add button and total dynamically?

How can I add a Total TextView inside ListView, as well as a Save Button under the ListView, dynamically?
Total is to be displayed similar to the following image. (note: not my data representation)
Activity A (Code Snippet)
long as=0; // for total
long bs=0;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
// receive from B
switch (requestCode)
{
case 0:
result = data.getStringExtra("text"); // holds value (34,24)
name = data.getStringExtra("a"); // Project
as = as+Long.parseLong(result); // For total amount
Text = " " + name + " " + "RM" + result + ""; // display in listView
if (mClickedPosition == -1) {
//add new list
m_listItems.add(Text);
m_listBitmapItems.add(Global.img);
} else {
// edit listView value and image
m_listItems.set(mClickedPosition, Text);
m_listBitmapItems.set(mClickedPosition, Global.img);
}
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;
case 1: // Another name
result = data.getStringExtra("text");
name = data.getStringExtra("a");
description = data.getStringExtra("c");
bs = bs + Long.parseLong(result);
Log.d("FIRST", "result:" + result);
Text = " " + name + " " + "RM" + result + "";
if (mClickedPosition == -1)
{
m_listItems.add(Text);
} else {
m_listItems.set(mClickedPosition, Text);
}
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;
}
}
long samount = as + bs;
Toast.makeText(getActivity(), samount + "", Toast.LENGTH_LONG).show();
}
Activity A (Rendered Output)
Here I would like to add a Total TextView with value 58 (output as RM58), as well as a Save Button.
I am using the following xml files.
a.xml
<?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">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="#string/text"
android:textSize="20sp" />
<ListView android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
claims.xml (inside the listView)
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageView android:id="#+id/imageView4"
android:layout_width="101dp"
android:layout_height="50dp" />
</AbsoluteLayout>
Thanks.
Add the following footer.xml file to res/layout http://developer.android.com/reference/android/widget/ListView.html
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent
android:orientation="vertical" >
// Format as you please
<TextView
android:id="#+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="Total" />
</LinearLayout>
In your activity create and initialise the following variables.
LayoutInflater inflater = getLayoutInflater();
ViewGroup footer = (ViewGroup) inflater.inflate(R.layout.footer, listView,
false);
// You can add this when an item is added and remove it if the list is empty.
listView.addFooterView(footer, null, false);
tv = (TextView)footer.findViewById(R.id.tv);
// Update the text.
tv.append("t/"+ results.toString());
As mentioned in the comments, you can either use long total as a static class member and update it with the results value total+=results; taking care to reset the value to zero or decrement it if an item is removed from the list.
The other way is to loop through the items in your list, parsing the items to the object and getting the particular value of type long from each object and summing them as you go.
As you are now able to dynamically add your button, I'll add briefly for other users browsing, set the buttons visibility to GONE, so that the element does not displace the layout when it is not visible, HIDDEN makes the element not visible, but the space taken by the element affects the layout (and sometimes this is useful). Then the button visibility is dynamically changed to VISIBLE when an item is added to the list, and back to GONE when the list is cleared.
<Button
android:id="#+id/btn"
android:text="button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"/>
http://developer.android.com/reference/android/transition/Visibility.html

In Android get center of Relative Layout on API 10

I'm trying to find the center coordinates of a RelativeLayout that for the moment, is empty. I need to find the center before I can put anything into the Relative Layout. The Relative Layout is not the whole screen, so I can't use metrics to find the screen dimensions. Since my minimum API is 10, I can't use rLayout.getX() or rLayout.getY(). So what I've tried is:
int xScreenInt = gBoard_RL.getWidth()/2;
int yScreenInt = gBoard_RL.getHeight()/2;
int xInt = gBoard_RL.getLeft() + xScreenInt;
int yInt = gBoard_RL.getTop() + yScreenInt;
and all I get is 0,0. Does anyone have an any ideas how I can get this done? Here's my layout and the Activity so far:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/gb1_root_RL"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
tools:context=".GB1" >
<RelativeLayout
android:id="#+id/gb1_topInfo_RL"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="#drawable/blu_grade_bg"
android:orientation="vertical"
android:paddingBottom="15dp" >
<TextView
android:id="#+id/gb1_scValue_TV"
style="#style/mainScoreValueStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/gb1_score_TV"
android:layout_marginLeft="10dp" />
<TextView
android:id="#+id/gb1_timeValue_TV"
style="#style/mainTimeValueStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/gb1_time_TV"
android:layout_marginRight="10dp" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/gb1_gf_RL"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/gb1_topInfo_RL"
android:padding="10dp" >
</RelativeLayout>
the Relative Layout I need to find the center of is: android:id="#+id/gb1_gf_RL"
public class GB1 extends Activity {
TextView GScore_TV;
RelativeLayout gBoard_RL;
int xScreenInt, yScreenInt, xInt, yInt;
String xStr, yStr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
overridePendingTransition(R.anim.cutin, R.anim.cutout);
setContentView(R.layout.gb_layout);
GScore_TV = (TextView) findViewById(R.id.G1_scoreValue_TV);
gBoard_RL = (RelativeLayout) findViewById(R.id.gb1_gf_RL);
gBoard_RL.setBackgroundColor(Color.MAGENTA);
xScreenInt = gBoard_RL.getWidth()/2;
yScreenInt = gBoard_RL.getHeight()/2;
xInt = gBoard_RL.getLeft() + xScreenInt;
yInt = gBoard_RL.getTop() + yScreenInt;
xStr = String.valueOf(xInt);
yStr = String.valueOf(yInt);
GScore_TV.setText(xStr + ", " + yStr);
}
}
Try putting your code in a onGlobalLayout listener:
myRelativelayout.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
this.layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
//Your code here
}
});
EDIT:
Since, as #xorgate pointed out, the layout isnt drawn yet in the onCreate method. The onGlobalLayout method will be called when the layout is drawn and calculations such as yours should be done in there.
onCreate is called before a layout pass is done. All Views will have no size yet.
Try setting a global layout listener, and do the positioning code there.

Height of TextView is greater than the screen

I have a simple layout with a TextView in it. I am trying to estimate its dimensions (height and width) at run-time. The code I use is as follows:
Log.v(this.toString(), "Screen width = " + this.getResources().getDisplayMetrics().widthPixels + " and height = " + this.getResources().getDisplayMetrics().heightPixels);
Log.v(this.toString(), "TV width = " + tv.getWidth() + " and height = " + tv.getHeight());
Log.v(this.toString(), "TV raw width = " + tv.getMeasuredWidth() + " and raw height = " + tv.getMeasuredHeight());
Log.v(this.toString(), "TV width from display manager = " + getWindowManager().getDefaultDisplay().getWidth() + " and height = " + getWindowManager().getDefaultDisplay().getHeight());
tv.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
Log.v(this.toString(), "TV width from measurespec = " + tv.getMeasuredWidth() + " and height = " + tv.getMeasuredHeight());
tv.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#SuppressWarnings("deprecation")
#Override
public void onGlobalLayout() {
//get view height and width here.
Log.v(this.toString(), "Inside layout width and height measurer.");
Log.v(this.toString(), "In layout listener, TV width = " + tv.getWidth() + " and height = " + tv.getHeight());
tv.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
Log.v(this.toString(), "In layout listener, TV raw width = " + tv.getMeasuredWidth() + " and raw height = " + tv.getMeasuredHeight());
Log.v(this.toString(), "TV width from display manager = " + getWindowManager().getDefaultDisplay().getWidth() + " and height = " + getWindowManager().getDefaultDisplay().getHeight());
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
tv.getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
tv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
});
The phone I am testing it on is a Samsung Galaxy S Duos. In the LogCat, the height of the view is returned as 1058 pixels, which is greater than the phone's height of 800 pixels! The LogCat output is:
01-12 12:35:38.749: V/com.sriram.hellotts.HelloTTS#415f3ac8(18595): Screen width = 480 and height = 800
01-12 12:35:38.749: V/com.sriram.hellotts.HelloTTS#415f3ac8(18595): TV width = 0 and height = 0
01-12 12:35:38.749: V/com.sriram.hellotts.HelloTTS#415f3ac8(18595): TV raw width = 0 and raw height = 0
01-12 12:35:38.749: V/com.sriram.hellotts.HelloTTS#415f3ac8(18595): TV width from display manager = 480 and height = 800
01-12 12:35:38.759: V/com.sriram.hellotts.HelloTTS#415f3ac8(18595): TV width from measurespec = 48 and height = 32
01-12 12:35:38.929: V/com.sriram.hellotts.HelloTTS$1#41068c38(18595): In layout listener, TV width = 480 and height = 1112
01-12 12:35:38.959: V/com.sriram.hellotts.HelloTTS$1#41068c38(18595): In layout listener, TV raw width = 8518 and raw height = 59
01-12 12:35:38.959: V/com.sriram.hellotts.HelloTTS$1#41068c38(18595): TV width from display manager = 480 and height = 800
The layout is:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HelloTTS" >
<!-- Footer aligned with the bottom -->
<include
android:id="#+id/footerLayout"
layout="#layout/footer_ehtv_layout" />
<include
android:id="#+id/headerLayout"
layout="#layout/header_ehtv_layout" />
<SeekBar
android:id="#+id/seekbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true" />
<Button
android:id="#+id/submitText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_above="#id/seekbar"
android:text="#string/submit" />
<Button
android:id="#+id/nextPage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/submitText"
android:layout_alignBaseline="#id/submitText"
android:text="Next Page" />
<Button
android:id="#+id/previousPage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#id/submitText"
android:layout_toLeftOf="#id/submitText"
android:text="Prev. Page" />
<ScrollView
android:id="#+id/scrl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/submitText"
android:layout_below="#id/headerLayout">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tv"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:inputType="none"
android:clickable="true"
android:longClickable="true"
android:textIsSelectable="true"
android:scrollbars="vertical"
android:textSize="15sp" />
</RelativeLayout>
</ScrollView>
</RelativeLayout>
My question(s):
1. How is this even possible?
2. What else can I do to ensure that the TextView height and width are returned correctly, that is, after the layout has been drawn.
Further, the TextView will only be displayed in portrait mode.
I have tried this sample.
Display display = this.getWindowManager().getDefaultDisplay();
int height=display.getHeight(); //you can get height
int weight=display.getWidth(); //you can get width
if(display.getHeight()==480&&display.getWidth()==320){
}
else if(display.getHeight()==800&&display.getWidth()==480){
}
else if(display.getHeight()==320&&display.getWidth()==240){
}

Categories

Resources