日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

android动态添加标签,android – 动态添加Textview

發(fā)布時間:2025/4/16 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 android动态添加标签,android – 动态添加Textview 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

在布局文件中,我有以下內(nèi)容:

android:layout_width="100dp"

android:layout_height="wrap_content" android:layout_marginRight="10dp"

android:text="SYN"

android:textAppearance="?android:attr/textAppearanceMedium"

android:background="@drawable/rectanglepurple"

android:textColor="#000000"

android:gravity="right"/>

我試圖使用代碼實(shí)現(xiàn)以下目標(biāo),到目前為止我有:

Resources res = getResources();

Drawable drawable1=res.getDrawable(R.drawable.rectanglepurple);

TextView idText = new TextView(getActivity());

idText.setText("SYN");

idText.setTextAppearance(getActivity(), android.R.style.TextAppearance_Medium);

idText.setTextColor(Color.BLACK);

idText.setGravity(Gravity.RIGHT);

idText.setBackgroundDrawable(drawable1);

我不能鍛煉如何處理

android:layout_width="100dp"

android:layout_height="wrap_content" android:layout_marginRight="10dp"

任何幫助贊賞.

解決方法:

這是Android布局的一個有趣部分.以layout_為前綴的XML屬性實(shí)際上用于包含視圖管理器(如LinearLayout或RelativeLayout).所以你需要添加這樣的東西:

//convert from pixels (accepted by LayoutParams) to dp

int px = convertDpToPixel(100, this);

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(px, LinearLayout.LayoutParams.WRAP_CONTENT);

//convert from pixels (taken by LayoutParams.rightMargin) to dp

px = convertDpToPixel(10, this);

params.rightMargin = px;

idText.setLayoutParams(params);

并且convertDpToPixel(無恥地適應(yīng)(改為返回int而不是float)從Converting pixels to dp):

/**

* This method converts dp unit to equivalent device specific value in pixels.

*

* @param dp A value in dp(Device independent pixels) unit. Which we need to convert into pixels

* @param context Context to get resources and device specific display metrics

* @return An integer value to represent Pixels equivalent to dp according to device

*/

public static int convertDpToPixel(float dp, Context context) {

Resources resources = context.getResources();

DisplayMetrics metrics = resources.getDisplayMetrics();

int px = (int) (dp * (metrics.densityDpi / 160f));

return px;

}

編輯:將分配更改為rightMargin從10(像素?cái)?shù))更改為變量px(包含10dp中的像素?cái)?shù))whoopsie.

標(biāo)簽:android,android-layout,android-textview

來源: https://codeday.me/bug/20190729/1570877.html

《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀

總結(jié)

以上是生活随笔為你收集整理的android动态添加标签,android – 动态添加Textview的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。