簡體   English   中英

自定義視圖如何訪問變量?

[英]Custom View how to access variable?

我在Google地圖上創建了自定義視圖,我想在最上面的信息上添加用戶單擊的內容,而自定義視圖存在很大的問題,即如何從活動中訪問變量。

 public class Shop extends LinearLayout {

    private TextView name;

    public Shop(Context context) {
        super(context);
        setContentView();
    }

    public Shop(Context context, AttributeSet attrs) {
        super(context, attrs);
        setContentView();
    }

    public Shop(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setContentView();
    }

    private void setContentView() {

        LayoutInflater layoutInflater =    (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.list_item_display_brand, this);


        name = (TextView) view.findViewById(R.id.shop);
        name.setText(".");

  }

    public void shopSetText() {
        name.setText("PetShop");

    }

}

我加入了活動:

public class MapViewActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstance) {
        super.onCreate(savedInstance);
        setContentView(R.layout.activity_map);

        Shop map = new Shop(getApplicationContext());

        map.shopSetText();
    }

'為什么不能通過shopSetText設置名稱? 現在只顯示“。”

更改此:

public void shopSetText() {
    name.setText("PetShop");
}

至:

 public void shopSetText(String sTextToSet) {
    name.setText(sTextToSet);
}

在您的活動中:

public class MapViewActivity extends Activity {

@Override
public void onCreate(Bundle savedInstance) {
    super.onCreate(savedInstance);
    setContentView(R.layout.activity_map);

    Shop map = new Shop(getApplicationContext());

    map.shopSetText("Same text to set here. Lorem ipsum");
}

而不是在Shop類的shopSetText()方法內部

public void shopSetText() {
    name.setText("PetShop");

}

public void shopSetText() {
    LayoutInflater layoutInflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = layoutInflater.inflate(R.layout.list_item_display_brand, this);
    name = (TextView) view.findViewById(R.id.shop);
    name.setText("PetShop");

}

像第一個一樣(您現在正在做),您剛剛創建了一個名為nameTextView對象,但尚未找到要與之鏈接的布局的任何TextView 。您需要對shopSetText方法執行相同的shopSetText ,就像您為setContentView方法所做的。

暫無
暫無

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

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