2017-04-11 171 views
0

簡單的問題,爲什麼發生這種情況?無法解析符號(字符串)

import android.media.MediaPlayer; 
import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.Button; 

import com.maxiesnax.gavinisms2.gavinisms2.R; 



public class GavinFragment extends Fragment { 
; 



@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    View rootView = inflater.inflate(R.layout.fragment_gavin, container, 
false); 



    // Inflate the layout for this fragment 
    return rootView; 

    final MediaPlayer aahMP = MediaPlayer.create(getActivity(), R.raw.aaah); 

    Button play_aaah = (Button) getActivity().findViewById(R.id.play_ahhh); 

    play_aaah.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      aahMP.start(); 
     } 
    }); 

} 


} 

這是我的包含aah.mp3按鈕的Fragment的代碼。錯誤發生在

(R.id.play_ahhh); 

特別是play_ahhh,它已經在XML中定義了。

<resources> 
<string name="app_name">Gavinisms</string> 

<string name="navigation_drawer_open">Open navigation drawer</string> 
<string name="navigation_drawer_close">Close navigation drawer</string> 

<string name="action_settings">Settings</string> 

<string name="play_ahhh">Ahhh"</string> 
<!-- TODO: Remove or change this placeholder text --> 
<string name="hello_blank_fragment">Hello blank fragment</string> 
</resources> 
+0

'play_ahhh',就像你定義的那樣,它將在'R.string'中,而不是'R.id'。這就是爲什麼你得到「無法解析符號」錯誤。但是您沒有在您設置的文本中找到「視圖」。你可以通過他們的ID找到他們;即,您在佈局中設置的'android:id'屬性的值。 –

回答

0

更改

<string name="play_ahhh">Ahhh"</string> 

<string name="play_ahhh">Ahhh</string> 

你也應該使用片段rootView

Button play_aaah = (Button) rootView.findViewById(R.id.play_ahhh); 
return rootView; 
0

在下面一行除去雙引號內的文字,

<string name="play_ahhh">Ahhh"</string 

更改爲,

<string name="play_ahhh">Ahhh</string 
0
<string name="play_ahhh">Ahhh</string> 

我也找到代碼中一個可能的錯誤...

// Inflate the layout for this fragment 
return rootView; 

移動此行onCreateView()函數的底部。它不會在return語句後執行代碼。我還會建議你閱讀一些java相關書籍,比如「用Java思考」。