Android - 在代码中应用 9 补丁

发布于 2025-01-07 06:25:53 字数 694 浏览 3 评论 0原文

如何在代码中将 9 补丁应用到 Android TextView?

你可能会问为什么?因为我需要动态设置控件的数量。

我尝试做类似的事情,但它不起作用:(

代码中我的9补丁“notif_bubble_white.9.png”是R.drawable.notif_bubble_white)

  tv = new TextView(this); 
  tv.setText("Test Message"); 
  tv.setLayoutParams(lpL); 
  tv.setPadding(0, 0, paddingValue, 0); 
  CustomFonts.ApplyFont_Custom1(tv, context); 
  tv.setBackgroundResource(R.drawable.notif_bubble_white); 
  // tv.setTextColor(TxtColFromCl); 
  layout.addView(tv); 

其中lpL定义为:

  LinearLayout.LayoutParams lpL = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 
        LinearLayout.LayoutParams.WRAP_CONTENT); 

How may I apply a 9 patch to an Android TextView IN CODE?

Why, you may ask? Because I need to dynamically set the number of controls.

I'm try to do something similar and its not working:

(my 9 patch "notif_bubble_white.9.png" in code is R.drawable.notif_bubble_white)

  tv = new TextView(this); 
  tv.setText("Test Message"); 
  tv.setLayoutParams(lpL); 
  tv.setPadding(0, 0, paddingValue, 0); 
  CustomFonts.ApplyFont_Custom1(tv, context); 
  tv.setBackgroundResource(R.drawable.notif_bubble_white); 
  // tv.setTextColor(TxtColFromCl); 
  layout.addView(tv); 

where lpL was defined as:

  LinearLayout.LayoutParams lpL = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 
        LinearLayout.LayoutParams.WRAP_CONTENT); 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

霓裳挽歌倾城醉 2025-01-14 06:25:53

您可以一次性创建所有控件,并使用 control.setVisibility(View.GONE) 隐藏它们直到需要为止,或者,如果控件的数量未知,您可以膨胀布局文件,例如此问题中进行了描述。

从引用的问题复制的代码(归功于 Cedric、或 Pentium10、idk,并假设控件是一个按钮):

button.xml:

<Button
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/button01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

膨胀按钮:

button = (Button) getLayoutInflater().inflate(R.layout.button, null);

You can either just create the controls all at once and hide them with control.setVisibility(View.GONE) until needed, or, if the number of controls are unknown, you can inflate a layout file, like described in this question.

Code copied from referenced question (credits to Cedric, or Pentium10, idk, and assuming control is a button):

button.xml:

<Button
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/button01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

Inflating the button:

button = (Button) getLayoutInflater().inflate(R.layout.button, null);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文