Как программно найти TextView на ListActivity - PullRequest
0 голосов
/ 24 марта 2012

У меня есть ListActivity, и я хочу программно установить текст TextView, который находится внутри моего макета, мне нужно сделать это для всех моих строк.

В этом TextView будет отображаться символ валюты для текущей локали в каждой строке ListActivity.

Фрагмент кода:

DepositoRepository repo = new DepositoRepository(this);
Cursor c = repo.getCursor();
adapter = new SimpleCursorAdapter(this, R.layout.deposito_list, c,
    new String[] { Deposito.COLUNA_VALOR, Deposito.COLUNA_DATA },
    new int[] { R.id.tvValorDeposito, R.id.tvDataDeposito });
setListAdapter(adapter);

Что я хочу для всех строк:

Currency moeda = Currency.getInstance(Locale.getDefault());
TextView tvMoeda = (TextView)findViewById(R.id.tvMoeda);
tvMoeda.setText(moeda.getSymbol(Locale.getDefault()));

Ответы [ 2 ]

3 голосов
/ 24 марта 2012

Вы можете использовать пользовательский адаптер для вашего listView. Если хотите, я могу отредактировать свой ответ и показать вам, как это сделать. Вот то, что может поставить вас на правильный путь. Адаптируйте этот код к вашему приложению. А из вашей деятельности просто вызовите setListAdapter (адаптер), адаптер является вашим собственным адаптером.

Надеюсь, это поможет!

EDIT:

import java.util.Currency;
import java.util.Locale;

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;

public class CustomAdapter extends CursorAdapter{

    public CustomAdapter(Context context, Cursor c) {
        super(context, c);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        Currency moeda = Currency.getInstance(Locale.getDefault());
        TextView tvMoeda = (TextView)view.findViewById(R.your_id);//your textView id here
        tvMoeda.setText(moeda.getSymbol(Locale.getDefault()));
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.item, parent, false);//your layout here
        bindView(v, context, cursor);
        return v;
    }

}
1 голос
/ 24 марта 2012

Простой пример упражнения, в котором отображается список всех внутренних музыкальных файлов (мелодии и т. Д.).

MyActivity.java

public class MyActivity extends Activity {
    private MyCursorAdapter mAdapter;

    // that's what we want to know from the database
    private static final String[] PROJECTION = new String[] {
        MediaStore.Audio.AudioColumns._ID,   // 0 - _id must be present
        MediaStore.Audio.AudioColumns.TITLE, // 1
        MediaStore.Audio.AudioColumns.DATA   // 2
    };
    // those from above - no need for cursor.getColumnIndex()
    private static final int TITLE_IDX = 1;
    private static final int TEXT_IDX = 2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ListView lv = (ListView) findViewById(R.id.list_view);
        mAdapter = new MyCursorAdapter(this, TITLE_IDX, TEXT_IDX);
        lv.setAdapter(mAdapter);

        loadContent();
    }

    // would be better to do in a Loader, AsyncTask, ...
    private void loadContent() {
        ContentResolver cr = getContentResolver();
        Cursor c = cr.query(
                    MediaStore.Audio.Media.INTERNAL_CONTENT_URI,
                    PROJECTION, null, null, null
                );
        mAdapter.changeCursor(c);
    }
}

MyCursorAdapter.java
в этом классе нет реальной зависимости от курсора, он очень похож на SimpleCursorAdapter

public class MyCursorAdapter extends CursorAdapter {
    private final LayoutInflater mInflater;
    private final int mTitleIdx, mTextIdx;

    /**
     * Creates a new MyCursorAdapter. Set cursor via  changeCursor / swapCursor
     * @param context <code>this</code> will usually do
     * @param titleColumnIdx cursor columnindex to be displayed as title
     * @param textColumnIdx  cursor columnindex to be displayed as text below
     */
    public MyCursorAdapter(Context context, int titleColumnIdx, int textColumnIdx) {
        super(context, null, false);
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mTitleIdx = titleColumnIdx;
        mTextIdx = textColumnIdx;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        TextView title = (TextView) view.findViewById(R.id.title);
        TextView text = (TextView) view.findViewById(R.id.text);
        title.setText(cursor.getString(mTitleIdx));
        text.setText(cursor.getString(mTextIdx));
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        View item = mInflater.inflate(R.layout.list_item, null);
        // could do static init here / attach holder / set onClickListeners, ...
        return item;
    }
}

main.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="fill_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/list_view"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
        <!-- Preview: listitem=@layout/list_item -->
    </ListView>

</LinearLayout>

list_item.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="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textAppearance="@android:style/TextAppearance.Large"
        android:textColor="@android:color/primary_text_dark"
        android:layout_marginTop="5dp" />

    <TextView
        android:id="@+id/text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textAppearance="@android:style/TextAppearance.Small"
        android:textColor="@android:color/secondary_text_dark"
        android:singleLine="true"
        android:ellipsize="end"
        android:layout_marginBottom="5dp" />

</LinearLayout>

Что вы получаете

result

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