簡體   English   中英

如何訪問Adapter類中的Activity對象

[英]How to access Activity object in Adapter class

我如何訪問基適配器類中的活動對象。 我使用適配器類作為我的列表視圖的適配器。 我想訪問列表視圖之外的文本視圖,但列表視圖和文本視圖處於同一活動中。 我在適配器類中嘗試過這樣的:

            holder.grandTotal = (TextView) ShopCartActivity.findViewById(R.id.txtGrandTotal);
        holder.grandTotal.setText(String.valueOf(new DecimalFormat("##.##").format(grandTotal)));

但是此語法出現錯誤:

ShopCartActivity. //ERROR

我也試過這樣:

ShopCartActivity.this or ShopCartActivity.class

我在適配器類的構造函數中嘗試了這個它可以工作(但尚未計算值)但是當我將它放入我所有計算都在其中進行的 getView() 方法中時,它不起作用。

基本上我想在循環返回基本適配器中的值后設置 textview 的值。 有沒有辦法可以使用 findviewbyid 方法訪問對象?

不應嘗試從適配器內訪問活動。 這是糟糕的編程。 如果您想向 Activity 傳遞一些值並在其中執行一些操作,請使用某種回調機制(抽象類或接口)將值傳遞給 Activity,然后讓 Activity 更新TextView的文本。

使用抽象類的示例代碼:

public abstract class AdapterHandler
{
    public void updateText(String text) {}
}

然后在Adapter中創建這個類的對象:

public AdapterHandler adapterhandler;

然后在Activity設置處理程序,初始化適配器后:

adapter.adapterhandler = new AdapterHandler() {
    @Override
    public void updateText(String text) {
        ShopCartActivity.this.grandTotal.setText(text);
    }
};

然后在適配器中,在需要的地方,像這樣調用它:

if (this.adapterhandler != null) {
    this.adapterhandler.updateText(String.valueOf(new DecimalFormat("##.##").format(grandTotal)));
}

代碼相對較長,但這是正確且更具可擴展性的方法。

創建適配器時傳遞上下文,使用該上下文獲取膨脹視圖。

Adapter adapter = new Adapter(this);

然后在 Adpater 類構造函數中:

public Adapter(Context context){
context.findViewById(R.id.textview);
}

如果您有來自 Activity 的上下文,您可以像這樣在 ListView 之外獲取 TextView 和其他視圖:

// Get the rootView from the activity
final View rootView = ((Activity)mContext).getWindow().getDecorView().findViewById(android.R.id.content);

// Get the textView from the rootView
TextView mTextView = rootView.findViewById(R.id.your_text_view);

// Do something with it
mTextView.setText("Hello my friend!");

您可以在調用構造函數時設置適配器之前從類中發送任何對象,然后可以在適配器中接收這些參數。

final ChannelsAdapter channelAdapter = new ChannelsAdapter(allChannelList, SoftKeyboard.this);
channelRecyclerView.setAdapter(channelAdapter);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM