gpt4 book ai didi

java - 自定义View如何访问变量?

转载 作者:行者123 更新时间:2023-12-01 12:34:19 25 4
gpt4 key购买 nike

我创建了自定义 View ,在谷歌地图上我想在顶部信息上添加用户点击的内容,但我在自定义 View 方面遇到了大问题,如何从 Activity 访问变量。

 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");

}

}

我添加到 Activity 中:

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

在您的 Activity 中:

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

关于java - 自定义View如何访问变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25704391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com