2014-09-06 24 views
0

我在谷歌地圖上創建了自定義視圖我想在頂部信息上添加什麼是用戶點擊的東西,並且我對自定義視圖有很大的問題,如何從活動訪問變量。自定義查看如何訪問變量?

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集的名字嗎?現在它只顯示「。」

回答

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

裏面方法shopSetText()Shop類,而不是做

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

} 

通過這樣做像第一個(你正在做的現在)你剛纔創建的TextView對象調用name但沒有發現任何TextView的佈局與它鏈接。您需要爲shopSetText方法做同樣的操作,就像您對setContentView方法所做的一樣。

+0

謝謝,我那樣做,但它也沒有幫助。 奇怪的是,我可以改變它只從構造函數 – shiwon 2014-09-07 06:37:56