【发布时间】:2017-09-21 17:30:24
【问题描述】:
我想以编程方式在当前视图中添加一个 TextView。我知道如何在创建新布局时创建它,但我想将其添加到当前布局中,主要问题是如何获取对 main_activity 布局的引用。
感谢您的回答。
【问题讨论】:
-
把你的代码放在这里
-
M.Tarek 我看到了这个帖子,但是当我想重拍这个时我没有理由。
我想以编程方式在当前视图中添加一个 TextView。我知道如何在创建新布局时创建它,但我想将其添加到当前布局中,主要问题是如何获取对 main_activity 布局的引用。
感谢您的回答。
【问题讨论】:
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");
}
【讨论】:
假设您的项目中有一个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);
}
}
【讨论】: