- 布局中动态添加View
在项目中经常会出现自定义的View,并且添加到指定布局中,中间出现过不少问题,现在我给大家详细说下,希望可以帮助大家
废话多说了,直接看代码
布局文件;activity_main.xml
<LinearLayout
android:id="@+id/viewObj"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#cccccc"
android:orientation="vertical" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal" >
<EditText
android:id="@+id/textContent"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="输入要发送的内容" />
<Button
android:id="@+id/sendContent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送" />
</LinearLayout>
下面是java代码:MainActivity.java
viewObj = (LinearLayout) findViewById(R.id.viewObj);
textContent = (EditText) findViewById(R.id.textContent);
sendContent = (Button) findViewById(R.id.sendContent);
sendContent.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String content = textContent.getText().toString().trim();
if (content.length() <= 0) {
Toast.makeText(MainActivity.this, "请输入要发送的内容",
Toast.LENGTH_LONG).show();
return;
} else {
viewObj.addView(getContent(content));
textContent.setText("");
}
}
});
java代码中需要一个自定义的方法来显示添加的内容 如下:
public TextView getContent(String text) {
TextView textView = new TextView(MainActivity.this);
textView.setText(text);
textView.setTextSize(20);
textView.setTextColor(Color.RED);
textView.setGravity(Gravity.CENTER);
textView.setSingleLine(true);
return textView;
}
好了,代码到这里就完成了,一个简单的demo,希望可以帮到大家,下面是截图效果