目前我的應用由EditText
和一個按鈕組成,兩者均位於屏幕底部。如果我在EditText
中鍵入內容,並且在屏幕頂部創建了TextView
,則按下該按鈕。在上方添加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;
}
我需要改變什麼才能看起來像我想要的那樣?
當您說使用LinearLayout作爲父視圖時,您的意思是我應該用LinearLayout替換RelativLayout,並將edittext和按鈕放入它? – nummer92
是的絕對,Edittext和Button將從底部開始的第一個兩個索引,所以每次插入你的textview設置索引爲3 –
所以我想我也要說:linearLayout.addView(button,1)和linearLayout.addView(edittext, 1)。因爲沒有我的按鈕在頂部,而edttext在底部 – nummer92