Как добавить EditText в ListView - PullRequest
       2

Как добавить EditText в ListView

0 голосов
/ 21 сентября 2011

Я хочу прочитать некоторые сведения о продукте из базы данных, а затем добавить их в ListView.

Затем я хочу, чтобы в каждой строке было поле Кол-во EditText, где клиент может добавить кол-во. Как я могу это сделать?Я сделал простую страницу, но при вводе кол-во, прокрутки вниз, а затем обратно вверх я теряю данные, или они даже появляются в другом поле кол-во в другой строке.

Ответы [ 3 ]

1 голос
/ 21 сентября 2011

Хорошо, поэтому первое, что вам нужно сделать, это создать файл Row.xml для макета, который вы хотите, чтобы каждая строка в списке имела ..

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
 android:layout_height="wrap_content"
android:orientation="horizontal"
>
<ImageView
android:id="@+id/icon"
android:padding="2dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ok"
/>
<TextView
android:id="@+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="40sp"
/>
//Add a edittext here..
/LinearLayout>

Далее вам нужно будет расширить представление списка и переопределить представление get для загрузки в пользовательскую строку.

public class Demo extends ListActivity {

@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
setListAdapter(new Adapter());}

//Here extends a ArrayAdapter to create your custom view
class Adapter extends ArrayAdapter<String> {
Adapter() {
super(DynamicDemo.this, R.layout.row, R.id.label, items);
}
public View getView(int position, View convertView,
ViewGroup parent) {
//Here load in your views such as the edittext

}

То, что вам нужно для начала, вы можете затем вызывать onItemListClick (), чтобы получать каждый клик, когда пользователь щелкает элемент.

Вы можете получить полное руководство здесь ...

Учебник

EDIT:

Также, если вы хотите сохранить число в поле количества, вам понадобится комплект. Такие как Метод saveState ()

Это сохранит количество ваших пользователей, пока приложение еще живо, и когда вы вернетесь в поле зрения, вытащите число или целое число из пакета.

Это должно помочь

http://www.edumobile.org/android/android-beginner-tutorials/state-persistence/

0 голосов
/ 22 сентября 2011

Привет, ниже код, с которым я играл

package sanderson.swords.mobilesales;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.OnItemClickListener;

public class OrderProductSearch extends ListActivity {

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    try{
    setContentView(R.layout.orderproducts);
    }
    catch (Exception e) {
        //
        String shaw="";
        shaw = e.getMessage();
    }

    //Create view of the list where content will be stored
    final ListView listContent = (ListView)findViewById(R.id.orderproductlistview); 

    //Set for fast scrolling 
    listContent.setFastScrollEnabled(true);

    //Create instance of the database
    final DbAdapter db = new DbAdapter(this); 

    //Open the Database and read from it
    db.openToRead();

    //Routine to call all product sub groups from the database
    final Cursor cursor = db.getAllSubGroupProduct();

    //Manages the cursor
    startManagingCursor(cursor);  

    //The columns we want to bound
    String[] from = new String[]{DbAdapter.KEY_PRNAME, 
            DbAdapter.KEY_PRSIZE, DbAdapter.KEY_PKQTY};

    //This is the id of the view that the list will be map to
   int[] to = new int[]{R.id.productlinerow, R.id.productlinerow2, R.id.productlinerow3};

    //Create simple cursor adapter
    SimpleCursorAdapter cursorAdapter = 
        new SimpleCursorAdapter(this, R.layout.productlinerow, cursor, from, to);

    //Set the cursor to the list content view
    listContent.setAdapter(cursorAdapter);

    //Close the database
    db.close();     

    //check if any orders are on the system
    int check = cursor.getCount();

    AlertDialog.Builder ps = new AlertDialog.Builder(OrderProductSearch.this);
    final Button border = (Button) findViewById(R.id.orderqty);


    //notify the user if there are no orders on the system
    if (check == 0)
    {
    ps.setTitle("No Products Found");
    ps.setMessage("There are no products in this group");
    ps.setPositiveButton("Ok", new DialogInterface.OnClickListener(){     
    public void onClick(DialogInterface dialog, int which) 
    {         
        OrderProductSearch.this.finish();
        startActivity(new Intent("sanderson.swords.mobilesales.PRODUCTENQUIRY"));
    } 
    }); 
        ps.show();
    }


    border.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {
            try {
                String clicked = "";
                clicked = "neil shaw";

            } catch (Exception e) {
                String error = e.getMessage();
                error = error + "";
            }
        }
    });
0 голосов
/ 21 сентября 2011

Вы должны сохранить состояние (контент, введенный пользователем в EditText) в какой-то массив, предоставленный вашему списку адаптера.Возможно, вы создаете новый EditText в методе getView () вашего адаптера списка.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...