Androidでテキスト表示に省略記号があるか否かを判断する判断

1988 ワード

いくつかのテキスト展示クラスの需要に対して、常に最大展示行数(maxLines)を設定することを要求して、テキストの長さが展示する最大内容より大きい時省略記号が現れて、同時に省略記号が現れるかどうかによっていくつかのその他の操作をして、例えば“全文”などの字を表示して、しかし後に全文をクリックしてすべての内容を表示することを要求します.このとき,テキストが最大表示量をオーバーフローしたか否かを判断する必要があり,レイアウトファイルにTextViewの最大行数5,android:maxLines=5を設定する独自の実装方法を提供する.
実装:
Layout layout = ((TextView) holder.getView(R.id.content)).getLayout();
		if (layout != null) {
			int lineCount = layout.getLineCount();//     note2       5(    )  
			if (lineCount > 5) {//  note2     
				holder.setVisibility(R.id.content_showfull, View.VISIBLE);
			} else {
				int ellipsisCount = layout.getEllipsisCount(lineCount - 1);//  note2   0
				if (ellipsisCount > 0) {
					holder.setVisibility(R.id.content_showfull, View.VISIBLE);
				} else {
					holder.setVisibility(R.id.content_showfull, View.GONE);
				}
			}
		} else {
			ViewTreeObserver observer = holder.getView(R.id.content).getViewTreeObserver();
			if (observer.isAlive()) {
				observer.addOnPreDrawListener(
						new ViewTreeObserver.OnPreDrawListener() {
							@Override
							public boolean onPreDraw() {
								Layout layout = ((TextView) holder.getView(R.id.content)).getLayout();
								if (layout != null) {
									int lineCount = layout.getLineCount();
									if (lineCount > 5) {
										holder.setVisibility(R.id.content_showfull, View.VISIBLE);
									} else {
										int ellipsisCount = layout.getEllipsisCount(lineCount - 1);
										if (ellipsisCount > 0) {
											holder.setVisibility(R.id.content_showfull, View.VISIBLE);
										} else {
											holder.setVisibility(R.id.content_showfull, View.GONE);
										}
									}
								} else {
									holder.setVisibility(R.id.content_showfull, View.GONE);
								}
								try {
									(holder.getView(R.id.content).getViewTreeObserver()).removeOnPreDrawListener(this);
								} catch (Exception e) {
									e.printStackTrace();
								}
								return true;
							}
						}
				);
			}
		}