当我点击 ListFragment 内的 EditText(请参阅“您的答案......”字段是下面的屏幕截图)时,它不会保持焦点,这使得它无法使用。一旦文本光标出现在 EditText 字段上,它就会迅速消失,并且 EditText 字段失去焦点。
我发现很少有相关的堆栈帖子,并且怀疑某些东西可能会从 EditText 中窃取焦点。在此处查看相关帖子。我也读过关于强迫焦点的帖子,但没有任何意义。
我可以以编程方式构建视图,但是使用标准 ListFragment 和 ArrayAdapter 代码要容易得多。该列表将随着用户输入而增长,并且使用 Android 提供的基础架构更易于管理。
请参阅下面的屏幕。屏幕右侧是一个 ListFragment,其中包含行的自定义布局。每行包含一个 EditText 和一个用于提交文本的 Button。
这是 ListFragment 的代码:
public class ItemDetailFragment extends ListFragment {
/**
* The fragment argument representing the item ID that this fragment
* represents.
*/
public static final String ARG_ITEM_ID = "item_id";
private static final String STATE_ACTIVATED_POSITION = "activated_position";
/**
* The dummy content this fragment is presenting.
*/
private static DetailArrayAdapter mAdapter;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public ItemDetailFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<DetailData> items = new ArrayList<DetailData>();
items.add(new DetailData("1"));
mAdapter = new DetailArrayAdapter(getActivity(), R.layout.detail_layout, items);
// TODO: replace with a real list adapter.
setListAdapter(mAdapter);
}
class DetailArrayAdapter extends ArrayAdapter<DetailData> {
Context context = null;
int layoutResourceId;
ArrayList<DetailData> data;
public DetailArrayAdapter(Context context, int layoutResourceId, ArrayList<DetailData> data){
super(context, layoutResourceId, data);
this.context = context;
this.layoutResourceId = layoutResourceId;
this.data = data;
}
public View getView(int position, View convertView, ViewGroup parent){
View row = convertView;
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
DetailData data = this.data.get(position);
EditText text = (EditText) row.findViewById(R.id.answer);
text.setText(data.detail_number + "You answer here ...");
Button submit_button = (Button) row.findViewById(R.id.answer_submit);
submit_button.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
int count = mAdapter.getCount();
int item_num = count + 1;
DetailData d = new DetailData(""+item_num);
mAdapter.add(d);
}
});
return row;
}
}
class DetailData {
public String detail_number;
public DetailData(String num){
this.detail_number = num;
}
}
}
这是自定义行的布局代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<EditText
android:id="@+id/answer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Your answer here..."
android:maxLines="1"
android:singleLine="true"/>
<Button
android:id="@+id/answer_submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go" />
</LinearLayout>