Sundus Bokhari Sundus Bokhari - 11 days ago 5
Android Question

Getting focus of Edittext drawn programatically in Android

I am trying to draw edit text programatically,based on my JSON response.All are drawn perfectly,but i can only edit the last one and the others are not editable ,and I can't get their focus. Any idea what would fix this?

RelativeLayout layout =(RelativeLayout)getActivity().findViewById(R.id.layout_items);
JSONArray result=(JSONArray)o;
for (int i = 0; i < result.length(); i++) {
try {
relativeLayoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);

editText = new EditText(context);
editText.setHint(result.getJSONObject(i).getString(config.TAG_NAME));
editText.setPadding(0,20,0,0);
editText.setId(Integer.parseInt(result.getJSONObject(i).getString(config.TAG_ID)));
editText.setEnabled(true);
editText.setFocusableInTouchMode(true);
editText.requestFocus();
relativeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
relativeLayoutParams.addRule(RelativeLayout.CENTER_VERTICAL);
relativeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, layout.getId());
layout.addView(editText, relativeLayoutParams);
}
catch (Exception ex) {
}
}
}

Answer

Try with Linear Layout:

    LinearLayout layout = (LinearLayout) getActivity().findViewById(R.id.layout_items);
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    JSONArray result = (JSONArray) o;
    for (int i = 0; i < result.length(); i++) {
        EditText editText = new EditText(context);
        editText.setHint(result.getJSONObject(i).getString(config.TAG_NAME));
        editText.setPadding(0,i*100,0,0);
        editText.setId(Integer.parseInt(result.getJSONObject(i).getString(config.TAG_ID)));
        editText.setEnabled(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        editText.setLayoutParams(layoutParams);
        layout.addView(editText);
    }

And in your layout xml:

<LinearLayout
    android:id="@+id/layout_items"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"/>
Comments