2012-03-24 7 views
0

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

В этом текстовом режиме будет отображаться Символ обмена для текущего языка в каждой строке 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())); 
+1

Вы можете использовать реальный 'CursorAdapter', что позволяет манипулировать видом себя: HTTP: //thinkandroid.wordpress.com/2010/01/11/custom-cursoradapters/ – zapl

+0

Ммм ... Спасибо! Я попробую! – fvss

+0

одна вещь об этом примере: не расширяйте 'SimpleCursorAdaper', вместо этого используйте' CursorAdapter'. – zapl

ответ

3

Вы можете использовать пользовательский адаптер для вашего 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; 
    } 

} 
+0

Буду признателен, если вы сможете это сделать. – fvss

1

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

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; 
    } 
} 

основной. 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: [email protected]/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

Смежные вопросы