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

Posted

技术标签:

【中文标题】使用 ImageView 动态创建多个 EditText 并将 ImageView 点击值设置为 EditText 并从 EditText 获取值【英文标题】:Create dynamically multiple EditText with ImageView and set ImageView click value to EditText and get value from EditText 【发布时间】:2017-10-14 22:27:59 【问题描述】:

我想在按钮点击时动态创建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_
android:layout_
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_
    android:layout_
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:focusable="true"
    android:focusableInTouchMode="true"

    >

    <LinearLayout
        android:layout_
        android:layout_
        android:orientation="horizontal">

        <test.com.helpalert.MyEditText
            android:id="@+id/contact_one"
            android:layout_
            android:layout_
            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_
            android:layout_
            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_
        android:layout_
        android:orientation="horizontal">

        <test.com.helpalert.MyEditText
            android:id="@+id/contact_two"
            android:layout_
            android:layout_
            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_
            android:layout_
            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_
        android:layout_
        android:id="@+id/main_layout"
        android:orientation="horizontal"/>

    <LinearLayout
        android:layout_
        android:layout_
        android:gravity="center"
        android:id="@+id/image_btn_layout"
        android:orientation="vertical">

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

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

        <Button
            android:id="@+id/bt_submit"
            android:layout_
            android:layout_
            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>

获取联系人

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;


【问题讨论】:

那么,你的哪部分代码有问题? edittext 中显示电话号码,但我无法从 editText 获取数据。 【参考方案1】:

当您点击提交时,您应该循环查找所有添加的EditTexts 并从中获取价值。

试试这个:

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代替循环代码

【讨论】:

感谢@marmor,它正在工作。请告诉我如何在应用重新启动时保留该数据。我尝试过 sharedprefrecence 但它不起作用。 真的很有帮助。谢谢【参考方案2】:

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

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

我在这个网站上找到了另一个解决方案: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

【讨论】:

以上是关于使用 ImageView 动态创建多个 EditText 并将 ImageView 点击值设置为 EditText 并从 EditText 获取值的主要内容,如果未能解决你的问题,请参考以下文章

如何在动态 ImageView 上创建动态按钮,同时保持唯一性

在布局中正确排列多个图像(动态创建)

Android用代码动态创建TextView,EditText,ImageView工具类

android 存在数据库中的动态图片,如何读取出来,显示在ImageView中

将 OnLongClickListener 应用于具有相同名称的多个图像

Android UI - 用于水平绘制多个ImageView的布局