【问题标题】:Change view class programmatically以编程方式更改视图类
【发布时间】:2016-05-25 16:26:10
【问题描述】:

我正在使用 com.rockerhieu.emojicon 库,它工作得很好,但是当在带有长文本的 recyclerview 上使用时,滚动变慢。出于这个原因,我想在必须显示表情符号时使用 EmojiconTextView。所以,我想在我的 xml 资源上有一个 TextView 元素,并在需要时以编程方式将其转换为 EmojiconTextView。有没有办法做到这一点?我考虑过使用 ViewStub,但没有找到使用 TextView/EmojiconTextView 元素对其进行膨胀的方法。

提前致谢。

【问题讨论】:

    标签: android android-layout android-view textview android-inflate


    【解决方案1】:

    尝试以编程方式创建 UI,而不是使用 XML 创建 UI 的声明方式。

    考虑到您在 XML 中定义了 LinerLayout

    <LinearLayout
       android:id="@+id/linearMain"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:orientation="vertical">
    </LinearLayout>
    

    然后您可以通过编程方式添加您的EmojiconTextViewTextView

    final LinearLayout lm = (LinearLayout) findViewById(R.id.linearMain);
    
    LayoutParams lpView = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    
    if (mustShowEmoji) {
      EmojiconTextView etv = new EmojiconTextView(this);
      etv.setLayoutParams(lpView);
      etv.setText("TextView containing emoji");
      lm.addView(etv);        
    } else {
      TextView tv = new TextView(this);
      tv.setLayoutParams(lpView);
      tv.setText("TextView");
      lm .addView(tv);        
    }    
    

    【讨论】:

    • 感谢您的回答。我曾考虑过这样做,但后来我会在我的视图树上添加一个额外的视图组,我想避免这种情况。但是,目前这似乎是最好的解决方案。非常感谢
    猜你喜欢
    • 2021-09-03
    • 2014-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-17
    相关资源
    最近更新 更多