目前,我的应用程序由EditText
和按钮组成,位于屏幕底部。如果我在EditText
中输入内容并点击该按钮,则会在屏幕顶部创建TextView
。
但是,我想要实现的是,如果我点击该按钮,TextView
就会在EditText
字段正上方创建。如果我再次这样做,我希望第二个TextView
再次创建在EditText
之上,但低于另一个TextView
。
到目前为止,这是我的代码。
这里是xml :(这都在RelativeLayout
内。但出于某种原因,我无法将其放在此处,因为它未被检测为代码......)
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/linearLayout"
android:orientation="vertical" >
</LinearLayout>
<Button
android:id="@+id/button"
android:layout_width="100dp"
android:layout_height="50dp"
android:text="Senden"
android:layout_gravity="center_horizontal"
android:layout_alignBottom="@+id/editText"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="470px"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
我的活动:
public class MainActivity extends AppCompatActivity {
private Button button;
private EditText editText;
private LinearLayout linearLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
editText = (EditText) findViewById(R.id.editText);
button = (Button) findViewById(R.id.button);
final View.OnClickListener btnHandler = new View.OnClickListener() {
public void onClick(View v) {
String msg = editText.getText().toString();
editText.getText().clear();
linearLayout.addView(createNewTextView(msg));
View view = getCurrentFocus();
if(view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
};
button.setOnClickListener(btnHandler);
}
private TextView createNewTextView(String text) {
final LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(this);
textView.setLayoutParams(lparams);
textView.setTextColor(Color.BLACK);
textView.setText(text);
return textView;
}
我需要改变什么才能让它看起来像我想要的那样?
答案 0 :(得分:1)
使用LinearLayout
作为父视图
android:gravity="center|bottom"
这个属性。
现在,在添加文本视图时,插入新创建的文本视图和位置。
parentLinearLayout.addView(childtextview, index); //index represents it position in linearlayout,according to you index is always 2.
答案 1 :(得分:0)
很多观点都有很好的控制权:RecyclerView。使用if处理文本视图,并使用LinearLayoutManager.setReverseLayout(true)将视图放在容器底部