android动态创建文本视图

时间:2015-04-01 09:39:15

标签: 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>

当我在手机上运行时,它说,&#34;不幸的是,该应用已经停止&#34;

2 个答案:

答案 0 :(得分:3)

更改订单

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

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

答案 1 :(得分: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. 您可以使用相同的代码进行多个文本视图。