andriod 動態設定TextView 和 RelativeLayou 高度,andriodtextview
1 XML布局 2 <RelativeLayout 3 android:id="@+id/rlay_meeting_contact_context" 4 android:layout_width="match_parent" 5 android:layout_height="44dp" 6 android:clickable="false" 7 android:focusable="false" > 8 9 <TextView10 android:id="@+id/tv_test"11 >12 android:layout_width="match_parent"13 android:layout_height="match_parent"14 android:layout_alignParentTop="true"15 android:layout_toRightOf="@+id/TextView07"16 android:duplicateParentState="true"17 android:gravity="left|center"18 android:singleLine="true"19 android:text="@string/accept_invite_this_troop" />20 21 </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);
1 private TextView mtvTest;2 3 mtvTest= (TextView) findViewById(R.id.tv_test);
利用timer計時器擷取:LineCount
註:getLineCount注意:需要待對象展開後才能正確擷取,不然擷取到的是0
1 TimerTask task = new TimerTask() { 2 public void run() { 3 Message message = new Message(); 4 message.what = 1; 5 handler.sendMessage(message); 6 } 7 }; 8 9 final Handler handler = new Handler() {10 public void handleMessage(Message msg) {11 switch (msg.what) {12 case 1:13 android.util.Log.e("Timer", "Timer");14 update();15 break;16 }17 super.handleMessage(msg);18 }19 20 };21 22 private void update() {23 int linecount = mtvTest.getLineCount();24 25 Log.i("tv.getLineCount()", mtvTest.getHeight() + "");26 if ((!mLookContextflag) || (linecount < 2)) {27 28 mLookContextflag = true;29 mtvTest.setEllipsize(null); // 展開30 mtvTest.setSingleLine(false);31 } else if ((mLookContextflag) || (linecount > 1)) {32 mLookContextflag = false;33 if (mtvTestt.getLineCount() > 1) {34 int iHeght = mtvTest.getLineCount()35 * mtvTest.getLineHeight();36 37 if (iHeght > mContextHeght) {38 android.view.ViewGroup.LayoutParams pp = mrlayMeetingContactContext39 .getLayoutParams();40 pp.height = iHeght;41 mrlayMeetingContactContext.setLayoutParams(pp);42 mMeetingContactContext.setHeight(iHeght);43 //timer用完結束掉44 if (mTimer != null) {45 mTimer.cancel();46 mTimer = null;47 }48 }49 50 }51 52 }
調用:
1 @Override 2 public void onClick(View v) { 3 // TODO Auto-generated method stub 4 switch (v.getId()) { 5 case R.id.meeting_contact_context: 6 if (mContextHeght == 0) { 7 mContextHeght = mrlayMeetingContactContext.getHeight(); 8 if (mTimer == null) { 9 mTimer = new Timer(false);10 mTimer.schedule(task, 10, 100);11 }12 }13 }