2015-04-01 80 views
-1

我是android新手。只是玩基本的东西。这里是我的代码android动态创建文本视图

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    linearLayout = (LinearLayout) findViewById(R.id.linearLayout); 
    setContentView(R.layout.activity_display_message); 
    // Get the message from the intent 
    Intent intent = getIntent(); 
    String status = intent.getStringExtra(MyActivity.EXTRA_MESSAGE); 

    TextView textView = new TextView(this); 
    textView.setTextSize(40); 
    textView.setText(status); 
    textView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
    linearLayout.addView(textView); 
} 

XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/linearLayout" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="#ff99ccff" 
    android:orientation="vertical" > 
</LinearLayout> 

当我我的手机上运行这个它说, “不幸的是,该应用程序已停止”

+0

Post Logcat请 – Amsheer 2015-04-01 09:41:28

+0

这部分代码是错误的String status = intent.getStringExtra(MyActivity.EXTRA_MESSAGE);显示Logcat请 – Arlind 2015-04-01 09:53:50

回答

3

更改像

setContentView(R.layout.activity_display_message); 
linearLayout = (LinearLayout) findViewById(R.id.linearLayout); 
顺序

您必须首先setContentView(...),然后初始化Views

+0

谢谢,它的工作原理。你能告诉我两者有什么区别吗? – 2015-04-01 09:51:50

+0

@BenZRayne仔细阅读我的答案。您必须先设置内容视图。 (窗口),然后你从那里初始化视图。 – 2015-04-01 09:52:59

1

您可以还有其他的方式动态地添加文本视图:

  1. 您的活动中创建方法:

    private TextView getCustomTextView(Context context, String tvValue, String tvHint) { 
    
        TextView textView = new TextView(context); 
        textView.setText("" + tvValue); 
        textView.setTextColor(context.getResources().getColor(R.color.black)); 
        textView.setTextSize(20); 
    
        // to set font family 
        Typeface face = Typeface.createFromAsset(getAssets(), 
          "fonts/epimodem.ttf"); 
        textView.setTypeface(face); 
    
        textView.setHint(tvHint+""); // static 
        textView.setHint(context.getString(R.string.text_hint)); // from string file 
        textView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
        return textView; 
    
    } 
    
  2. 添加文本视图中的LinearLayout。

    linearLayout.addView(getCustomTextView(this, "text value in string", "hint value in string"));

  3. 您也可以使用相同的代码不止一个文本视图。