2013-07-20 136 views
4

我試圖在片段中更改android中ImageButton的源代碼。從片段獲取資源

我想使用Image.setImageResource()方法,但是我不能在片段中使用getResources()。有沒有辦法解決這個問題? getActivity()。getResources()不會返回任何不幸的結果。

我試過寫了一個字符串,如「R.drawable」。 + {不同的圖像名稱},但我不能將該字符串轉換爲int。

這還能做什麼?

我只是想改變一些imageButtons與源文件依賴於不同的事情。

回答

7

我得到這個工作在一個片段:

int imageresource = getResources().getIdentifier("@drawable/your_image", "drawable", getActivity().getPackageName());   
    image.setImageResource(imageresource); 
+0

生病嘗試...謝謝:-) – AKTStudios

+0

此外,我們可以從XML使用資源。例如getActivity()。getResources()。getColor(R.color.rose) – Parthi

1

R.drawable.imagename是一個int。而setImageResource()採用int:

imageButton.setImageResource(R.drawable.imagename)

此外,這是奇怪的是,getActivity().getResources()將返回什麼。如果你的Fragment被附加到一個Activity中,它應該返回一個Resources對象。

+0

嗯也許它只是沒有返回我的圖像,我會再試一次... – AKTStudios

+0

@AKTStudios'getActivity()。getResources()'應該工作,因爲' getResources'需要活動上下文。發佈您的實施。 – Raghunandan

+0

也許你應該看看我的答案,它適用於我 – Simon

0

我們可以利用的資源onCreateView(...)方法:

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    View rootView = inflater.inflate(R.layout.layout_name, container, false); 
    int sizeView = rootView.getResources().getDimension(R.dimen.size_view)); 
    return view; 
}