【发布时间】:2017-08-08 16:43:49
【问题描述】:
我已经通过包含LinearLayout 的代码创建了布局,其中我有一个TextView 一个EditText 三个Buttons 分别是添加、删除和设置以及一个TextView 当我单击添加按钮时EditText 被添加到布局中。当我单击删除按钮时,从布局中删除EditText,当我单击设置按钮时,将各种编辑文本中的文本设置为TextView。我无法将字符串从各种EditText 附加到TextView。
这是我的代码
package com.example.rushikesh.assignment3;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView textView;
EditText edt;
Button btnAdd, btnRemove,btnSet;
LinearLayout linearLayout;
EditText editText;
int count = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
textView = new TextView(this);
textView.setLayoutParams(layoutParams);
edt = new EditText(this);
edt.setLayoutParams(layoutParams);
btnAdd = new Button(this);
btnAdd.setLayoutParams(layoutParams);
btnAdd.setText("+");
btnRemove = new Button(this);
btnRemove.setLayoutParams(layoutParams);
btnRemove.setText("-");
btnSet = new Button(this);
btnSet.setLayoutParams(layoutParams);
btnSet.setText("SET");
linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setLayoutParams(layoutParams);
linearLayout.addView(textView);
linearLayout.addView(edt);
linearLayout.addView(btnAdd);
linearLayout.addView(btnRemove);
linearLayout.addView(btnSet);
setContentView(linearLayout);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
editText = new EditText(MainActivity.this);
editText.setLayoutParams(layoutParams);
linearLayout.addView(editText);
count++;
}
});
btnRemove.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(count > 0)
{
linearLayout.removeViewAt(5);
count--;
}else
{
Toast.makeText(MainActivity.this, "No edit text found", Toast.LENGTH_SHORT).show();
}
}
});
btnSet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
}
【问题讨论】:
-
对布局使用 XML。重用 layoutParams 对象是完全错误的,因为每个 View 都必须有自己对应的 LayoutParams。使用 XML 进行布局可以为您处理所有这些事情,让您的主代码保持干净。
-
我完全同意你的观点,我们必须使用 XML 来创建布局。但是问题陈述就像我们被告知通过代码创建布局
-
@AkshayNaik 你可以同时做这两件事。您使用 xml 布局作为模板,在 java 中对其进行膨胀,然后将其添加到您想要的任何视图中。见
LayoutInflater.from(Context...).inflate(layout.xml, ..., ...)。
标签: android android-layout android-edittext textview