【问题标题】:How to add programmatically TextView in current layout [duplicate]如何在当前布局中以编程方式添加 TextView [重复]
【发布时间】:2017-09-21 17:30:24
【问题描述】:

我想以编程方式在当前视图中添加一个 TextView。我知道如何在创建新布局时创建它,但我想将其添加到当前布局中,主要问题是如何获取对 main_activity 布局的引用。

感谢您的回答。

【问题讨论】:

  • 把你的代码放在这里
  • M.Tarek 我看到了这个帖子,但是当我想重拍这个时我没有理由。

标签: java android


【解决方案1】:
private boolean tuVariable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.completar_perfil);
        if(tuVariable){ //si tu variable es true
            TextView textView = new TextView(this);
            textView.setText("you message");
        }

【讨论】:

    【解决方案2】:

    假设您的项目中有一个LinearLayout,如下所示:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:id="@+id/main"
    android:layout_height="wrap_content" 
    android:orientation="vertical">
    </LinearLayout>
    

    要在布局中添加多个TextView's,您可以执行以下操作:

    public class YourActivity extends Activity {
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            View linearLayout =  findViewById(R.id.main);
    
    
            TextView valueTV = new TextView(this);
            valueTV.setText("hallo hallo");
            valueTV.setId(5);
            valueTV.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
    
            ((LinearLayout) linearLayout).addView(valueTV);
        }
    }
    

    【讨论】:

    • 据我了解,此代码将文本视图添加到新的线性布局。我想向这个 setContentView(R.layout.main); 添加一个 textView我创建了主应用程序视图,在 onCreate 内部我有检查变量的条件,如果为 true,则将额外的 textView 添加到当前视图
    • 是一样的东西兄弟,你可以找到你的布局,并在上面添加你的 TextView。我编辑了我的答案
    • 谢谢它完美运行 :) 告诉我每个布局或按钮等在 View 之后继承?比如java中String、Integer等在Object之后继承?
    • 是的,除了一个例外,Relative Layout、LinearLayout、FrameLayout 等布局管理器从 ViewGroup 继承,而 ViewGroup 类在 View 之后继承:D 你能接受答案吗?
    • 可能我破坏了一些东西。当我想查找布局 View linearLayout = findViewById(R.id.activity_main);我无权访问activity_main,但是当我尝试类似 View linearLayout = findViewById(R.layout.activity_main);这是禁止的行为。我应该添加 main_activity 代码吗?
    猜你喜欢
    • 1970-01-01
    • 2013-07-06
    • 1970-01-01
    • 2013-04-29
    • 1970-01-01
    • 2017-07-16
    • 1970-01-01
    • 1970-01-01
    • 2011-03-14
    相关资源
    最近更新 更多