如何添加文本视图以响应按钮单击(用户输入的字符串)



我想在我的自动完成文本视图下面显示用户按下旁边的按钮时输入的内容。所以基本上添加一个文本视图来响应按钮点击。我有"hello world"显示我现在想要它们的位置,但被困在如何在按钮侦听器中执行此操作。任何帮助,非常感谢。

这是我试图完成的确切内容的图像示例。

样品展示

我的创建到目前为止:

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView textView = new TextView(this);
    textView.setText("hello world");
    LinearLayout linearLayout = (LinearLayout) findViewById(R.id.activity_main);
    //LayoutParams is a class to specify layout properties when adding a view to a layout
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
    linearLayout.addView(textView, layoutParams);
  }
}

用于布局的 XML:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.example.tester.MainActivity">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <AutoCompleteTextView
            android:text="AutoCompleteTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/autoCompleteTextView"
            android:layout_weight="1" />
        <Button
            android:text="PRESS ME"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/button2"
            android:layout_weight="1" />
    </LinearLayout>
</LinearLayout>

试试这个

Button button1 = (Button) findViewById(R.id.button2);
AutocompleteTextView autoTv = (autocompleteTextView) findViewById(R.id.autocompleteTextView);
button1.setOnClickListener(new View.OnClickListener() {
  @Override public void onClick(View v) {
    String enteredText = autoTv.getText().toString();
    if (!enteredText.isEmpty()) {
      TextView textView = new TextView(this);
      textView.setText(enteredText);
      LinearLayout linearLayout = (LinearLayout) findViewById(R.id.activity_main);
      //LayoutParams is a class to specify layout properties when adding a view to a layout
      LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
          LinearLayout.LayoutParams.WRAP_CONTENT);
      linearLayout.addView(textView, layoutParams);
    }
  }
});

相关内容

  • 没有找到相关文章

最新更新