Метод getView () ArrayAdapter автоматически вызывается при событии фокуса EditText - PullRequest
0 голосов
/ 01 июля 2011

Я создаю пользовательский список действий.Есть два класса, один из которых имеет расширенную ListActivity, а другой - ArrayAdapter для этой активности списка.

Проблема 1: Проблема в том, что при открытии экрана ListActivity у меня есть поле поиска поверх него.Когда я запускаю ListActivity, он автоматически открывает клавиатуру, когда текущий фокус находится на EditText .Я хочу это остановить.

Проблема 2: Также, когда фокус переходит на EditText, метод ArrayAdapter getView () вызывается автоматически, который снова генерирует все строки,Я не понимаю, почему так происходит.Я также не вызываю notifyDataSetchanged () метод.Тем не менее, когда я сосредотачиваюсь на EditText, getView () вызывается автоматически.Как это предотвратить?

storelistview.xml:

<?xml version="1.0" encoding="UTF-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@color/black" android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:focusable="true" android:focusableInTouchMode="true">
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <TableRow android:id="@+id/tableRow2" android:layout_height="wrap_content"
            android:gravity="center" android:layout_width="fill_parent"
            android:background="#919191">
                <EditText android:id="@+id/searchText" android:layout_width="fill_parent"
                    android:layout_height="wrap_content" android:width="240dp"
                    android:hint="Search"></EditText>
                <ImageView android:layout_width="wrap_content"
                    android:src="@drawable/search" android:layout_height="wrap_content"
                    android:id="@+id/searchImage"></ImageView>
    </TableRow> 
</TableLayout>
<ListView android:id="@+id/android:list" android:layout_width="fill_parent"
    android:layout_height="fill_parent"/>
<TextView android:id="@+id/android:empty"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:textColor="@color/white" android:textSize="14sp"
    android:gravity="top|center" android:text="No store found.." /></LinearLayout>

StoreListView.java:

public class StoreListView extends ListActivity {

private List<Store> stores = new ArrayList<Store>();
private StoreListRowAdapter rowAdapter;
private Runnable fetchStores;
private Handler handler = new Handler();
private ImageView searchImage;
private EditText searchText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.storelistview);

    searchText = (EditText) findViewById(R.id.searchText);
    searchImage = (ImageView) findViewById(R.id.searchImage);
    searchImage.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            }

        }
    });

    rowAdapter = new StoreListRowAdapter(this, R.layout.storelistview, stores);
    setListAdapter(rowAdapter);

    fetchStores = new Runnable() {

        @Override
        public void run() {
            Store store = new Store();
            StoreListAsynTask s = new StoreListAsynTask();
            s.execute(store);
        }
    };

    handler.post(fetchStores);

}

private Runnable resultThread = new Runnable() {

    public void run() {
        rowAdapter.clear();
        for (int i = 0; i < stores.size(); i++) {
            Store bean = stores.get(i);
            rowAdapter.add(bean);
        }
        //rowAdapter.notifyDataSetChanged();
    }
};

class StoreListAsynTask extends AsyncTask<Store, Void, String> {

    private Gson gson = new Gson();
    private List<Store> storeList;
    private ProgressDialog m_ProgressDialog = null;

    @Override
    protected String doInBackground(Store... params) {
                 return respData;
    }

    @Override
    protected void onPostExecute(String result) {
                    //populate store list
        stores = storeList;
        runOnUiThread(resultThread);
        m_ProgressDialog.dismiss();
    }

}

}

StoreListRowAdapter.java:

public class StoreListRowAdapter extends ArrayAdapter<Store> {

List<Store> stores;
public StoreListRowAdapter(Context context, int textViewResourceId, List<Store> stores) {
    super(context, textViewResourceId, stores);
    this.stores = stores; 
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = convertView;

    if (view == null) {
        LayoutInflater vi = (LayoutInflater) getContext().getSystemService(
                Context.LAYOUT_INFLATER_SERVICE);
        view = vi.inflate(R.layout.storelist_rowview, null);
    }

    final Store store = stores.get(position);
    if (store != null) {
        LinearLayout storeLogoContainer = (LinearLayout) view.findViewById(R.id.storeLogoContainer);
        LoaderImageView imageView = new LoaderImageView(getContext(), getContext().getString(R.string.logoUrl), store.getId().getId());
        storeLogoContainer.addView(imageView);

        TextView storeName = (TextView) view.findViewById(R.id.storeName);
        storeName.setText(store.getStoreName());            
    }
    return view;
}

}

Ответы [ 2 ]

3 голосов
/ 02 июля 2011

Когда я запускаю ListActivity, он автоматически открывает клавиатуру, так как текущий фокус находится на EditText. Я хочу остановить это.

Тогда сделайте что-то еще.

Кроме того, когда фокус переходит на EditText, автоматически вызывается метод getView () ArrayAdapter, который снова генерирует все строки.

getView() вызывается много раз. Это может или не может быть "генерация всех строк снова" Просто убедитесь, что ваша реализация getView() эффективна.

Как это предотвратить?

Вы нет. Просто убедитесь, что ваша реализация getView() эффективна.

1 голос
/ 17 октября 2011

когда мы используем ArrayAdapter для подачи TextView массивом объектов, ARE автоматически вызывает toString () для преобразования объекта массива в текст, который должен отображаться в текстовом представлении. Но для использования чего-то кроме TextViews дляотображение массива, например, ImageViews, или чтобы некоторые данные помимо результатов toString () заполняли представления, мы переопределяем getView (int, View, ViewGroup), чтобы возвращать тип представления, который вы хотите.Вызывается автоматически RE ..

...