andriod 动态设置TextView 和 RelativeLayou 高度

时间:2023-03-09 12:49:30
andriod 动态设置TextView 和 RelativeLayou 高度
 XML布局
<RelativeLayout
android:id="@+id/rlay_meeting_contact_context"
android:layout_width="match_parent"
android:layout_height="44dp"
android:clickable="false"
android:focusable="false" > <TextView
android:id="@+id/tv_test"
style="@style/B4_Font_white"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/TextView07"
android:duplicateParentState="true"
android:gravity="left|center"
android:singleLine="true"
android:text="@string/accept_invite_this_troop" /> </RelativeLayout>

注:android:gravity="left|center"//表示文本从左的中间开始,不然展开后文本会在中显开始显示

 

JAVA

定义:

private int mContextHeght = 0;
private Boolean mLookContextflag = false;

private RelativeLayout mrlayMeetingContactContext;
mrlayMeetingContactContext = (RelativeLayout) findViewById(R.id.rlay_meeting_contact_context);
 private TextView  mtvTest;

 mtvTest= (TextView) findViewById(R.id.tv_test);

利用timer计时器获取:LineCount

注:getLineCount注意:需要待对象展开后才能正确获取,不然获取到的是0

     TimerTask task = new TimerTask() {
public void run() {
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
}; final Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
android.util.Log.e("Timer", "Timer");
update();
break;
}
super.handleMessage(msg);
} }; private void update() {
int linecount = mtvTest.getLineCount(); Log.i("tv.getLineCount()", mtvTest.getHeight() + "");
if ((!mLookContextflag) || (linecount < 2)) { mLookContextflag = true;
mtvTest.setEllipsize(null); // 展开
mtvTest.setSingleLine(false);
} else if ((mLookContextflag) || (linecount > 1)) {
mLookContextflag = false;
if (mtvTestt.getLineCount() > 1) {
int iHeght = mtvTest.getLineCount()
* mtvTest.getLineHeight(); if (iHeght > mContextHeght) {
android.view.ViewGroup.LayoutParams pp = mrlayMeetingContactContext
.getLayoutParams();
pp.height = iHeght;
mrlayMeetingContactContext.setLayoutParams(pp);
mMeetingContactContext.setHeight(iHeght);
//timer用完结束掉
if (mTimer != null) {
mTimer.cancel();
mTimer = null;
}
} } }

调用:

     @Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.meeting_contact_context:
if (mContextHeght == 0) {
mContextHeght = mrlayMeetingContactContext.getHeight();
if (mTimer == null) {
mTimer = new Timer(false);
mTimer.schedule(task, 10, 100);
}
}
}