2015-04-01 78 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. 您也可以使用相同的代碼不止一個文本視圖。