使用ImageView动态创建多个EditText并将ImageView单击值设置为EditText并从EditText

时间:2017-05-16 01:49:37

标签: android android-layout android-imageview android-contacts savestate

我想在点击按钮时动态创建EditTextImageView

ImageView从联系人列表中选择单个联系人并设置为EditTextEditText也从用户那里获取价值。我想获取所有EditText的数据,并将值存储在SharedPreference

HelpAlertActivity

public class HelpAlertActivity extends AppCompatActivity implements View.OnClickListener {

public SharedPreferences sharedpreference;
LinearLayout add_new_layout, mainLayout, image_btn_layout, buttonLayout;
FrameLayout frameLayout;
Button btn_one, bt_submit;
MyEditText et_one, et_two, etAdd;
ImageView image_one, image_two;
ImageButton imageButton;
FloatingActionButton fab;
SharedPreferences.Editor editor;
List<MyEditText> allEds;
List<ImageView> allImg;
ImageView imageView;
String contactOne, contactTwo, number1, number2, number3, number4, number5, number6, number7, number8, number9, number10, number11,
        number12, number13;
StringBuilder stringBuilder;
GetContact mGetContact;
private int counter = 2, many = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_help_alert);
    initialization();
}

private void initialization() {
    sharedpreference = getSharedPreferences("preference", Context.MODE_APPEND);
    editor = sharedpreference.edit();

    mainLayout = (LinearLayout) findViewById(R.id.main_layout);
    image_btn_layout = (LinearLayout) findViewById(R.id.image_btn_layout);
   /* buttonLayout = (LinearLayout) findViewById(R.id.buttonLayout);
    add_new_layout = (LinearLayout) findViewById(R.id.newLayout);
    fab = (FloatingActionButton) findViewById(R.id.fab);*/
    mGetContact = new GetContact();
    et_one = (MyEditText) findViewById(R.id.contact_one);
    et_two = (MyEditText) findViewById(R.id.contact_two);
    image_one = (ImageView) findViewById(R.id.image_one);
    image_two = (ImageView) findViewById(R.id.image_two);
 //   btn_one = (Button) findViewById(R.id.btn_one);
    bt_submit = (Button) findViewById(R.id.bt_submit);
    image_one.setOnClickListener(this);
    image_two.setOnClickListener(this);
  //  btn_one.setOnClickListener(this);
    bt_submit.setOnClickListener(this);
    stringBuilder = new StringBuilder();

}

@Override
public void onClick(View v) {
    switch (v.getId()) {
     case R.id.btn_one:
            if (this.counter < 10) {
                LinearLayout parentView = (LinearLayout) this.findViewById(R.id.main_layout);
                LinearLayout childView = new LinearLayout(getApplicationContext());
                etAdd = generateEditText(counter+1);

                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(45, 45);
                layoutParams.setMargins(0, 25, 20, 0);
                imageView = new ImageView(this);
                imageView.setBackgroundResource(R.drawable.add_contact);
                imageView.setId(counter+1);
                imageView.setAdjustViewBounds(true);
                imageView.setLayoutParams(layoutParams);
                imageView.setOnClickListener(handler);
               /* imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), counter+1);
                    }
                });*/
                //getValue(imageView);

                allEds.add(etAdd);
                allImg.add(imageView);
                childView.addView(etAdd);
                childView.addView(imageView);
                parentView.addView(childView);

                counter++;
                //many++;
                //editor.putInt("no_of_layouts", many);
            } else {
                // v.setEnabled(false);
            }
            break;
        case R.id.image_one:
            startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), 1);
            break;
        case R.id.image_two:
            startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), 2);
            break;
        case R.id.bt_submit:
            String ctone = et_one.getText().toString();
            String ct_two = et_two.getText().toString();
            //int size = allEds.size();
            // String[] strings = new String[size];
           /* for (int i = 0; i < allEds.size(); i++) {

                strings[i] = allEds.get(i).getText().toString();

                editor.putString("contact" + i, strings[i]);
                Log.e("Added number", "" + i);
                // Toast.makeText(this, "contact" + i, Toast.LENGTH_SHORT).show();
            }*/
            if (ctone.equals("") && ctone.isEmpty() || ct_two.equals("") && ct_two.isEmpty()) {
                Toast.makeText(this, "Please enter mobile", Toast.LENGTH_SHORT).show();
            } else {
                editor.putString("contactOne", ctone);
                editor.putString("contactTwo", ct_two);
                editor.apply();
                Toast.makeText(this, "Contact Saved ", Toast.LENGTH_SHORT).show();
                startActivity(new Intent(this, MainActivity.class));
                //  }

                break;
            }
        /*case R.id.fab:
            buttonLayout.setVisibility(View.VISIBLE);
            image_btn_layout.setVisibility(View.VISIBLE);
            fab.setVisibility(View.INVISIBLE);
            break;*/
    }
}

View.OnClickListener handler = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case 3:
                startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), 3);
                break;
            case 4:
                startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), 4);
                break;
            case 5:
                startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), 5);
                break;
            case 6:
                startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), 6);
                break;
            case 7:
                startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), 7);
                break;
            case 8:
                startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), 8);
                break;
            case 9:
                startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), 9);
                break;
            case 10:
                startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), 10);
                break;
            case 11:
                startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), 11);
                break;
            case 12:
                startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), 12);
                break;
            case 13:
                startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), 13);
                break;
        }
    }
};
@Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
    super.onActivityResult(reqCode, resultCode, data);
    switch (reqCode) {
        case 1:
            if (resultCode == RESULT_OK) {
                String num = mGetContact.getdetails(data, getApplicationContext());
                Log.e("ADDED NUMBER", num);
                et_one.setText(num.replaceAll("[- ]", ""));
            }
            break;
        case 2:
            if (resultCode == RESULT_OK) {
                number2 = mGetContact.getdetails(data, getApplicationContext());
                Log.e("ADDED NUMBERo", number2);
                et_two.setText(number2.replaceAll("[- ]", ""));
            }
            break;
        case 3:
            if (resultCode == RESULT_OK) {
                number3 = mGetContact.getdetails(data, getApplicationContext());
                etAdd.setText(number3.replaceAll("[- ]", ""));
            }
            break;
        case 4:
            if (resultCode == RESULT_OK) {
                number4 = mGetContact.getdetails(data, getApplicationContext());
                etAdd.setText(number4.replaceAll("[- ]", ""));
            }
            break;
        case 5:
            if (resultCode == RESULT_OK) {
                number5 = mGetContact.getdetails(data, getApplicationContext());
                etAdd.setText(number5.replaceAll("[- ]", ""));
            }
            break;
        case 6:
            if (resultCode == RESULT_OK) {
                number6 = mGetContact.getdetails(data, getApplicationContext());
                etAdd.setText(number6.replaceAll("[- ]", ""));
            }
            break;
        case 7:
            if (resultCode == RESULT_OK) {
                number7 = mGetContact.getdetails(data, getApplicationContext());
                etAdd.setText(number7.replaceAll("[- ]", ""));
            }
            break;
        case 8:
            if (resultCode == RESULT_OK) {
                number8 = mGetContact.getdetails(data, getApplicationContext());
                etAdd.setText(number8.replaceAll("[- ]", ""));
            }
            break;
        case 9:
            if (resultCode == RESULT_OK) {
                number9 = mGetContact.getdetails(data, getApplicationContext());
                etAdd.setText(number9.replaceAll("[- ]", ""));
            }
            break;
        case 10:
            if (resultCode == RESULT_OK) {
                number10 = mGetContact.getdetails(data, getApplicationContext());
                etAdd.setText(number10.replaceAll("[- ]", ""));
            }
            break;
        case 11:
            if (resultCode == RESULT_OK) {
                number11 = mGetContact.getdetails(data, getApplicationContext());
                etAdd.setText(number11.replaceAll("[- ]", ""));
            }
            break;
        case 12:
            if (resultCode == RESULT_OK) {
                number12 = mGetContact.getdetails(data, getApplicationContext());
                etAdd.setText(number12.replaceAll("[- ]", ""));
            }
            break;
        case 13:
            if (resultCode == RESULT_OK) {
                number13 = mGetContact.getdetails(data, getApplicationContext());
                etAdd.setText(number13.replaceAll("[- ]", ""));
            }
            break;

    }

}

 public MyEditText generateEditText(int id) {
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(0, 90, 1.0f);
    layoutParams.setMargins(15, 10, 0, 0);
    MyEditText et = new MyEditText(this);
    et.setFilters(new InputFilter[]{new InputFilter.LengthFilter(13)});
    et.setBackgroundResource(R.drawable.login_textfield_background);
    et.setHint("Enter or Select number");
    et.setInputType(InputType.TYPE_CLASS_NUMBER);
    et.setPadding(35, 0, 30, 0);
    et.setId(id);
    et.setLayoutParams(layoutParams);
    return et;
}

 /* @Override
 protected void onResume() {
    super.onResume();
}*/

@Override
protected void onPause() {
    super.onPause();
   contactOne = sharedpreference.getString("contactOne", null);
   contactTwo = sharedpreference.getString("contactTwo", null);
    //*for (int i = 0; i < allEds.size(); i++) {
       // stringBuilder.append(sharedpreference.getString("contact" + i, "") + ",");
    }


@Override
protected void onResume() {
    super.onResume();
    et_one.setText(contactOne);
    et_two.setText(contactTwo);
    //* int size = allEds.size();
    // String[] strings = new String[size];
    // String[] lines = stringBuilder.toString().split(",");
    // for (String s : lines) {
    //  etAdd.setText(s);
 /**//*   strings[i] = allEds.get(i).getText().toString();
    sharedpreference.getString("contact" + i, "");*//**//*
    }*//*

}*/
}
}

/* public ImageView generateImageView(int id) {
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(45, 45);
layoutParams.setMargins(0, 25, 20, 0);
ImageView imageView = new ImageView(this);
imageView.setBackgroundResource(R.drawable.add_contact);
imageView.setId(id);
imageView.setAdjustViewBounds(true);
imageView.setLayoutParams(layoutParams);
return imageView;
}*/

acitivity_help_alert.xml

 <?xml version="1.0" encoding="utf-8"?>
<ScrollView android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:focusable="true"
    android:focusableInTouchMode="true"

    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <test.com.helpalert.MyEditText
            android:id="@+id/contact_one"
            android:layout_width="0dp"
            android:layout_height="60dp"
            android:layout_marginStart="10dp"
            android:layout_marginTop="10dp"
            android:layout_weight="1.0"
            android:freezesText="true"
            android:background="@drawable/login_textfield_background"
            android:hint="@string/contact_hint"
            android:inputType="number"
            android:paddingLeft="30dp"
            android:paddingRight="30dp"
            android:layout_marginLeft="10dp" />

        <ImageView
            android:id="@+id/image_one"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_marginEnd="10dp"
            android:layout_marginTop="35dp"
            android:adjustViewBounds="true"
            android:background="@drawable/add_contact"
            tools:ignore="ContentDescription"
            android:layout_marginRight="10dp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <test.com.helpalert.MyEditText
            android:id="@+id/contact_two"
            android:layout_width="0dp"
            android:layout_height="60dp"
            android:layout_marginStart="10dp"
            android:layout_marginTop="10dp"
            android:layout_weight="1.0"
            android:freezesText="true"
            android:background="@drawable/login_textfield_background"
            android:hint="@string/contact_hint"
            android:inputType="number"
            android:paddingLeft="30dp"
            android:paddingRight="30dp"
            android:layout_marginLeft="10dp" />

        <ImageView
            android:id="@+id/image_two"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_marginEnd="10dp"
            android:layout_marginTop="25dp"
            android:adjustViewBounds="true"
            android:background="@drawable/add_contact"
            tools:ignore="ContentDescription"
            android:layout_marginRight="10dp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/main_layout"
        android:orientation="horizontal"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:id="@+id/image_btn_layout"
        android:orientation="vertical">

        <Button
            android:id="@+id/btn_one"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_marginBottom="10dp"
            android:layout_marginTop="20dp"
            android:adjustViewBounds="true"
            android:background="@drawable/add_circular_button"
            tools:ignore="ContentDescription" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="10dp"
        android:gravity="center"
        >

        <Button
            android:id="@+id/bt_submit"
            android:layout_width="wrap_content"
            android:layout_height="46dp"
            android:layout_gravity="center_horizontal"
            android:background="@color/colorAccent"
            android:text="@string/btn_submit"
            android:layout_marginStart="20dp"
            android:layout_marginEnd="30dp"
            android:textColor="@color/white"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="30dp" />
    </LinearLayout>
</LinearLayout>

GetContact

public class GetContact {

String num = "";
public String getdetails(Intent data, Context applicationContext) {
    Cursor c = null;
    Cursor numbers = null;
    try {
        Uri contactData = data.getData();
         c = applicationContext.getContentResolver().query(contactData, null, null, null, null);
        if (c.moveToFirst()) {
            String contactId = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
            String hasNumber = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

            if (Integer.valueOf(hasNumber) == 1) {
                numbers = applicationContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
                while (numbers.moveToNext())
                    num = numbers.getString(numbers.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
        }
    }finally {
        if(c!=null  ){
            c.close();
        }
    }
    return num;
}
}

2 个答案:

答案 0 :(得分:1)

当您点击提交时,您应该循环搜索所有已添加的EditText并从中获取值。

试试这个:

String ct_one = et_one.getText().toString();
String ct_two = et_two.getText().toString();

List<String> strings = new ArrayList<>();
int index = 3; // the first dynamic id
MyEditText editText = (MyEditText) findViewById(index);
while (editText != null) {
    strings.add(editText.getText().toString());
}

Log.d("found strings: " + ct_one + ", " + ct_two + ", and: " + Arrays.toString(strings));

<强>更新

您的SharedPreferences代码有点奇怪,首先您应该使用PreferenceManager.getDefaultSharedPreferences,除非您有充分的理由使用其他文件。 第二,您应该在编辑后立即commit / apply进行编辑,而不是保留一个打开的编辑器对象。

写入值:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Editor editor = prefs.edit();
editor.putString("value_one", ct_one);
editor.putString("value_two", ct_two);
for (int i = 0; i < strings.size(); i++) {
    editor.putString("value" + i, strings.get(i));
}
editor.apply(); // actually saves the edits into the prefs file

读取值:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String ct_one = prefs.getString("value_one");
String ct_two = prefs.getString("value_two");
List<String> strings = new ArrayList<>();
int i = 0;
while (prefs.contains("value" + i)) {
    strings.add(prefs.getString("value" + i));
}

顺便说一句,如果字符串的顺序不重要,您可以使用putStringSet / getStringSet代替循环代码

答案 1 :(得分:0)

我有一个创建食谱的项目。当我添加食谱时,我可以具有多种成分和多种准备状态。

最大的问题是要知道多少个并将所有编辑文本存储在一个字符串中(我只存储一个带有换行符的字符串)。

我在此网站上找到了另一种解决方案:https://prasans.info/add-edittexts-dynamically-and-retrieve-values-android/

最简单的证明是从编辑文本的创建列表中进行,每次创建时都添加一个。最好的是,我现在可以为成分创建两个列表,为状态创建一个列表。

在活动开始时:

private ArrayList<EditText> ListEditText = new ArrayList<>();

创建新的编辑文本时(仅使用.addView):

ListEditText.add(new_editText);

要获取信息时:

String text = "";
for (EditText editText : ListEditText) {
  text += editText.getText().toString() + "\n";
}
// display text