how to set textview width wrap_content but limit to 1/3 of parent's width
basically, need to define width is wrap_content and the maxWidth does not go over 1/3.
If that's all you need, then my suggestion is to scrap the Weight approach and dynamically set the TextView's maxWidth
value.
Something like this:
tv.setMaxWidth(((LinearLayout)tv.getParent()).getWidth()/3);
I think that you'll have to dynamically check the parent layout width every time you update the textView, something like (I have tested this code using a button and edit text to change the textView - works without problem) :
<LinearLayout
android:id="@+id/myLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/tvA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="end"
/>
<TextView
android:id="@+id/tvB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="end"
/>
</LinearLayout>
code:
TextView tvA = (TextView) findViewById(R.id.tvA);
TextView tvB = (TextView) findViewById(R.id.tvB);
LinearLayout myLayout = (LinearLayout) findViewById(R.id.myLayout);
// code to use when the textView is updated
// possibly button onClickListener?
tvA.measure(0, 0);
int textWidth = tvA.getMeasuredWidth();
myLayout.measure(0,0);
int layoutWidth = myLayout.getWidth();
if (textWidth > (layoutWidth / 3)) {
tvA.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f));
tvB.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 2.0f));
} else {
tvA.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
tvB.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
}