【问题标题】:Creating a new TextView programmatically in a public class在公共类中以编程方式创建新的 TextView
【发布时间】:2014-04-11 09:49:10
【问题描述】:

我是Android新手,如果我的问题如此愚蠢,请道歉!

我在公共类中创建了一个新的 TextView,但是当我想为其分配 ID 时,[我尝试了 text1.setID(1)],但 Eclipse 无法识别 text1。

有什么问题?我是不是把 TextView 定义错了?

实际上我的目标是创建一个包含 2 个 textViews(text1 & text2) 的类(这里是 Class Post),然后我想在我的程序中从这个类创建对象(例如在主要活动中),这是一个正确的方法? (一种简单地创建新的android小部件)

public class Post{

Context Creator_Context;
public Post(Context context)
 {
    ctx= context;
 }

//Creating a textview.

TextView text1 = new TextView(Ctx);
TextView text2 = new TextView(Ctx);


///////here is the PROBLEM////// :

text1.setID(1);

}

谢谢,

【问题讨论】:

    标签: java android xml eclipse android-widget


    【解决方案1】:

    您可以尝试为您创建的 textView 设置标签。 (标签可以是字母数字字符串)

    textView.setTag("TAG-1");
    

    【讨论】:

      【解决方案2】:

      这不是您创建简单小部件所需遵循的方式。

      取而代之的是,一种更简单的方法是扩展现有组件并将您的 textview 放入其中。例如,您可以扩展 FrameLayout :

      public class TwoLinesTextButton extends FrameLayout {
      
      private TextView textView1;
      private TextView textView2;
      
      public TwoLinesTextButton(Context context, AttributeSet attrs) {
          super(context, attrs);
          initView(context, attrs);
      }
      
      public TwoLinesTextButton(Context context, AttributeSet attrs, int defStyle) {
          super(context, attrs, defStyle);
          initView(context, attrs);
      }
      
      
      public void fill(String text1, String text2) {
          textView1.setText(text1);
          textView2.setText(text2);
      }
      
      private void initView(Context context, AttributeSet attrs) {
      
          LayoutInflater infl = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
          View view = infl.inflate(getLayoutResource(), null);
      
      
          textView1 = (TextView) view.findViewById(R.id.text_1);
          textView2 = (TextView) view.findViewById(R.id.text_2);
      
          this.addView(view);
      }
      
      
      protected int getLayoutResource() {
          return R.layout.twolinestextbutton;
      }
      

      }

      在 layout/twolinestextbutton.xml 中:

      <?xml version="1.0" encoding="utf-8"?>
      

      <TextView
              android:id="@+id/text_1"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:maxWidth="250dp"/>
      
      <TextView
              android:id="@+id/text_2"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:maxWidth="250dp"/>
      

      【讨论】:

      • 查看我发布的示例,我创建了一个组件,其中有两个 TextView 一个在另一个
      • 这使得一种可以在您的代码或 layout.xml 文件中使用的小部件
      猜你喜欢
      • 2015-12-06
      • 2017-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-26
      • 2019-12-16
      • 1970-01-01
      • 2011-05-22
      相关资源
      最近更新 更多