2015-05-04 24 views
0

我已經使用XML文件中現有的編輯文本以編程方式創建了多個編輯文本,但是當主編輯文本獲得焦點時,動態創建的編輯文本也獲得焦點。我的代碼如下:以編程方式創建編輯文本也獲得焦點,同時攻擊Android中的另一個編輯文本

protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_worker_reg); 
     existingContact = (EditText)findViewById(R.id.workerPhone); 
     drawable = existingContact.getBackground(); 
    } 

public void addAnotherContactNumber(View view) { 
     final CharSequence[] options = { "Work", "Home","Cancel" }; 
     AlertDialog.Builder builder = new  AlertDialog.Builder(WorkerRegActivity.this); 
     builder.setTitle("Add Contact Number!"); 
     builder.setItems(options, new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialog, int item) { 
       if (options[item].equals("Work")) 
       { 
        linearLayout =  (LinearLayout)findViewById(R.id.containerLayout); 
        EditText newContact = new EditText(WorkerRegActivity.this); 
        newContact.setHint("Phone NO." + (newContactIndex - 1)); 
         newContact.setHintTextColor(existingContact.getHintTextColors()); 
        newContact.setInputType(existingContact.getInputType()); 
        newContact.setLayoutParams(existingContact.getLayoutParams()); 

        int sdk = android.os.Build.VERSION.SDK_INT; 
        if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) { 
         newContact.setBackgroundDrawable(drawable); 
        } else { 
         newContact.setBackground(drawable); 
        } 

        linearLayout.addView(newContact, newContactIndex); 
        newContactIndex += 1; 

        contactList.add(newContact); 

       } 
       else if (options[item].equals("Home")) 
       { 

       } 
       else if (options[item].equals("Cancel")) { 
        dialog.dismiss(); 
       } 
      } 
     }); 
     builder.show(); 
    } 

其實我想創建使用在與相同背景的XML文件中定義的,但是當一個編輯文本獲得焦點另一個也自動獲得焦點的現有編輯短信多個編輯文本。請幫助.....

回答

1

當你添加新的editTexts,只需添加一個屬性線關掉重點:

edittext.clearFocus(); 

其中的EditText是你的EditText的ID。

如果這行不通,你可以使用這個:

<!-- Dummy item to prevent AutoCompleteTextView from receiving focus --> 

<LinearLayout 
    android:focusable="true" android:focusableInTouchMode="true" 
    android:layout_width="0px" android:layout_height="0px"/> 

<!-- :nextFocusUp and :nextFocusLeft have been set to the id of this component 
    to prevent the dummy from receiving focus again --> 
<AutoCompleteTextView android:id="@+id/autotext" 
    android:layout_width="fill_parent" android:layout_height="wrap_content" 
    android:nextFocusUp="@id/autotext" android:nextFocusLeft="@id/autotext"/> 

這只是aworkaround欺騙安卓給予重點不是編輯文本別的東西。但請記住,您必須在您想撤銷焦點的editText之前放置虛擬元素。

+0

我已經做了,但它不工作 –

+0

請參閱已編輯的答案 –

0

在做這樣的事情時,我們應該使用drawable的不同對象而不是同一個實例。

Drawable clone = drawable.getConstantState().newDrawable();