簡體   English   中英

URI.parse和imagebutton錯誤

[英]URI.parse and imagebutton error

該代碼旨在在用戶單擊按鈕時打開Web視圖,但出現錯誤:

java.lang.NullPointerException: Attempt to invoke virtual method 'void     android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
    at info.teammumu.cougarcardapp.SocialMediaFragment.onCreateView(SocialMediaFragment.java:28)

對於Java代碼:

public class SocialMediaFragment extends Fragment {

public ImageButton fbbutton;
public ImageButton twbutton;
public ImageButton igbutton;

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

fbbutton = (ImageButton) getActivity().findViewById(R.id.fbbutton);
twbutton = (ImageButton) getActivity().findViewById(R.id.twbutton);
igbutton = (ImageButton) getActivity().findViewById(R.id.igbutton);

fbbutton.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/universityofhouston"));
        startActivity(browserIntent);
    }
});

twbutton.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("website"));
        startActivity(browserIntent);

    }});

igbutton.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("website"));
        startActivity(browserIntent);

    }});
return rootView;
}}

我之前曾問過這樣的問題,但從未得到回答,或者我聽不懂... 如何從imagebutton打開Webview? 感謝任何可以幫助您的人! 過去幾天,我一直在嘗試解決問題,但沒有成功。 它崩潰了,我無法打開任何標簽。

使用rootView而不是getActivity()onCreateView返回的Fragment布局訪問視圖:

fbbutton = (ImageButton) rootView.findViewById(R.id.fbbutton);
twbutton = (ImageButton) rootView.findViewById(R.id.twbutton);
.....

因為getActivity返回在其中添加了當前片段的Activity的上下文,所以調用getActivity().findViewById(<ID>)意味着從Activity Layout(而非Fragment getActivity().findViewById(<ID>)訪問視圖。

如果您在放大視圖的同時具有相同的按鈕,則應更改以下幾行:

fbbutton = (ImageButton) getActivity().findViewById(R.id.fbbutton);
twbutton = (ImageButton) getActivity().findViewById(R.id.twbutton);
igbutton = (ImageButton) getActivity().findViewById(R.id.igbutton);

像是 :

fbbutton = (ImageButton) rootView.findViewById(R.id.fbbutton);
twbutton = (ImageButton) rootView.findViewById(R.id.twbutton);
igbutton = (ImageButton) rootView.findViewById(R.id.igbutton);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM