Цель этого кода:Слушатель реализация: 3 EditTexts в одном фрагменте
У меня есть макет фрагмента с 3 EditTexts:
- Многоканальный Описание
- десятичное количество
- в Дата.
Я хочу, чтобы пользователь вводил эту информацию с помощью программной клавиатуры, а затем Fragment возвращал newItem (запись) в родительскую активность, чтобы ее можно было сохранить в db.
Я принимаю правильный подход, используя прослушиватель?
onEditorActionListener
кажется более гибким, чемonKeyListener
.Eclipse, на самом деле не устраивает линии:
descriptionEditText.setOnEditorActionListener(this);
жалуется, что
setOnEditorActionListener
не применяется с аргументами.
Я предполагаю, что это означает, что у меня есть проблема здесь:
public interface OnEditorActionListener {
public void onNewItemAdded(String[] newItem);
// need to change this newItem?
}
Другие комментарии приветствия, как это моя первая попытка попробовать это, и я уверен, что это ужасно.
Полный код ниже.
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
public class AddNewItemTextFragment extends Fragment {
// A Fragment event callback interface, pg 126 Meier; used to share info with host Activity
// Host activity listens for a new item to be created
public interface OnEditorActionListener {
public void onNewItemAdded(String[] newItem);
// need to change this newItem?
}
// Create a variable to store a reference to the parent Activity that will implement the interface.
private OnEditorActionListener onEditorActionListener;
// This reference can be retrieved as soon as the parent has been bound to the Fragment with the Fragment's onAttach handler.
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
onEditorActionListener = (OnEditorActionListener)activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + "must implement OnEditorActionListener");
}
}
// The Listener implementation
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstaceState) {
View view = inflater.inflate(R.layout.add_new_item_text_fragment , container, false);
final EditText descriptionEditText = (EditText)view.findViewById(R.id.description);
descriptionEditText.setOnEditorActionListener(this);
final EditText amountEditText = (EditText)view.findViewById(R.id.amount);
amountEditText.setOnEditorActionListener(this);
final EditText dateEditText = (EditText)view.findViewById(R.id.date1);
dateEditText.setOnEditorActionListener(this);
// add category, sub category Spinner
// need to add newItem as a parameter?
descriptionEditText.setOnEditorActionListener (new OnEditorActionListener() {
public boolean onEditorAction (TextView v, int actionId, KeyEvent event) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_SEND) {
String newDescription = descriptionEditText.getText().toString();
String newAmount = amountEditText.getText().toString();
String newDate = dateEditText.getText().toString();
// add other fields here; create array newItem containing all fields
String [] newItem ={newDescription, newAmount, newDate};
onEditorActionListener.onNewItemAdded(newItem);
handled = true;
}
return handled;
}
});
return view;
}
}
Великий, после прочтения всех ваши изменения мне понравились: суммировать, вы переименовали интерфейс (спасибо), и кнопка, которую вы добавили, «возвращает» всю запись, избегая необходимости в нескольких слушателях s (спасибо также за то, что выбрали мое оригинальное представление) – whitep