我创建了自定义视图,在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设置名称?现在它只显示"。"
答案 0 :(得分:1)
更改此内容:
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");
}
答案 1 :(得分:0)
shopSetText()
类的Shop
内部方法,而不是
public void shopSetText() {
name.setText("PetShop");
}
DO
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");
}
通过像第一个那样(你现在正在做),你刚刚创建了一个名为TextView
的{{1}}对象,但未找到任何name
布局要与它相关联。您需要对TextView
方法执行相同的操作,就像对shopSetText
方法一样。