片段中的浮动操作按钮中的NullPointerException

时间:2017-05-21 14:13:13

标签: android android-fragments nullpointerexception floating-action-button android-handler

你可以帮我解决这个错误:

var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    $( ".addresspicker" ).autocomplete({
      source: availableTags
    });
$('#modalIns').modal('show');
$( ".addresspicker" ).autocomplete( "option", "appendTo", ".eventInsForm" );

我想在片段中处理FAB,所以这里是代码:

FirstFragment.class

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                                                                    at com.sadface.tutorapp.FirstFragment.onCreateView(FirstFragment.java:23)

}

和fragment_first.xml:

public class FirstFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_first,
            container, false);
    FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
    return view;
}

我在stackoverflow上读到,我使用了view.findById,但它不起作用,我不明白是什么问题?

2 个答案:

答案 0 :(得分:0)

将其添加到xml中的FAB:

android:onClick:"nameOfMethod"

在你的片段中:

    public void nameofMethod(View v){
     //button Clicked
}

答案 1 :(得分:0)

您的代码似乎是正确的。我发现import pygame pygame.init() screen = pygame.display.set_mode((400, 400)) CENTER = (200, 200) RADIUS = 100 x = 0 y = 0 satelliteCenter = (CENTER[0]+RADIUS, CENTER[1]) run = 1 while run == 1: for event in pygame.event.get(): if event.type == pygame.QUIT: run = 0 pygame.quit() mouse = pygame.mouse.get_pos() vector = x-CENTER[0], y-CENTER[1] x +=1 distance = (vector[0]**2 + vector[1]**2)**0.5 if distance > 0: scalar = RADIUS / distance satelliteCenter = ( int(round( CENTER[0] + vector[0]*scalar )), int(round( CENTER[1] + vector[1]*scalar )) ) screen.fill((255,255,255)) pygame.draw.circle(screen, (71,153,192), CENTER, RADIUS) pygame.draw.circle(screen, (243,79,79), satelliteCenter, 16) pygame.display.update() 说:Android浮动操作按钮对滚动事件做出反应。当附加目标向上滚动时变为可见,向下滚动时变为不可见。

也许你应该使用一些可以滚动的布局。这是官方的例子:

FloatingActionButton

官方示例使用了listview。