Reputation: 4576
I have the following view:
<View
android:id="@+id/divider"
android:layout_height="2dp"
android:background="#ffffff"
android:layout_below="@+id/timer"
android:layout_width="wrap_content" />
I'm implementing a timer in my project. So, the function onTick() is called every second:
public void onTick(long millisUntilFinished) {
secsPassed++;
minsPassed = (secsPassed-1)/60;
View dividerWhite = findViewById(R.id.dividerWhite);
View divider = findViewById(R.id.divider);
Log.i("divider.getWdith() = ", divider.getWidth()-secsPassed + "");
Log.i("layout width ", divider.getLayoutParams().width + " ");
//further code to implement a timer
The problem is, I'm getting -1 for divider.getLayoutParams().width
while the value of divider.getWidth()
is correct (i.e., the seconds remaining)
I need to dynamically change the width of the view as the seconds pass. divider.setLayoutParams().width
is a good option to do that. But, it's not changing the layout width, which still remains -1
Upvotes: 2
Views: 1963
Reputation: 6588
getLayoutParams().width
returns -1 when the width is MATCH_PARENT
. getLayoutParams().width
can be FILL_PARENT
(replaced by MATCH_PARENT
, in API Level 8) or WRAP_CONTENT
or an exact size. But getWidth()
always returns the width in pixels.
Upvotes: 5
Reputation: 26034
Try using following code.
int widthSpec = View.MeasureSpec.makeMeasureSpec(View.MeasureSpec.UNSPECIFIED,
View.MeasureSpec.UNSPECIFIED);
viewObject.measure(widthSpec, widthSpec);
int height = viewObject.getMeasuredHeight();
int width = viewObject.getMeasuredWidth();
Upvotes: 0