gpt4 book ai didi

android - 以编程方式在 edittext 下方创建一个新的 textview

转载 作者:行者123 更新时间:2023-11-30 01:53:13 25 4
gpt4 key购买 nike

我有一个带有编辑文本和按钮的 Activity ,前一个具有属性

android:layout_weight="1"

当我按下按钮时,将以编程方式创建一个新的 TextView 。我希望新的 textview 出现在 edittext 下。使用我拥有的代码,每个 TextView 都在按钮的右侧创建。我怎样才能让它出现在我想要的地方,换行?我想,既然 textview 是由代码创建的,那么唯一的方法就是以编程方式。

这是我的activity.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:id="@+id/new_formulas"
>
<EditText
android:layout_weight="1"
android:textSize="30dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="@string/add_hint"
android:id="@+id/add_hint"
/>
<Button android:textSize="30dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/add"
android:id="@+id/add"
/>
</LinearLayout>

这是我的java代码:

public class New_set extends AppCompatActivity {
private LinearLayout mLayout;
private EditText mEditText;
private Button mButton;

public static int integer = 0;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_set);
mLayout = (LinearLayout) findViewById(R.id.new_formulas);
mEditText = (EditText) findViewById(R.id.add_hint);

mButton = (Button) findViewById(R.id.add);
mButton.setOnClickListener(onClick());
TextView textView = new TextView(this);
textView.setText(mEditText.getText().toString());
}

private OnClickListener onClick() {
return new OnClickListener() {

@Override
public void onClick(View v) {
createNewTextView(mEditText.getText().toString());
}
};
}

private void createNewTextView(String text) {
RelativeLayout layout = new RelativeLayout(this);

final TextView textView = new TextView(this);
textView.setId(integer);

textView.setText(text);

RelativeLayout.LayoutParams params1 =new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
if (integer > 1)
params1.addRule(RelativeLayout.BELOW, integer - 1);
else
params1.addRule(RelativeLayout.BELOW, R.id.add_hint);

layout.setLayoutParams(params1);
mLayout.addView(textView);
integer +=1;

}

我尝试使用 addRule 和 RelativeLayout 来实现它,但它不起作用。

最佳答案

你可以这样做

private void createNewTextView(String text) {
final TextView textView = new TextView(this);
textView.setId(integer);

textView.setText(text);

textView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mLayout.addView(textView,1);
integer +=1;

}

更新

如果你想添加多个textviews,我建议你添加一个ListView,然后在listview中添加textviews。

关于android - 以编程方式在 edittext 下方创建一个新的 textview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32694131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com