【问题标题】:how can I fix this button it can not go to the activity page?我该如何解决这个按钮它无法进入活动页面?
【发布时间】:2019-03-11 17:57:16
【问题描述】:
public class select_fragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_select, null);


    }
    private void button_parking(){

        Intent myIntent = new Intent(f, parking.class);
        startActivity(myIntent);
    }
}

【问题讨论】:

    标签: java android android-button


    【解决方案1】:

    试试这个...

    public class select_fragment extends Fragment {
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup 
    container, @Nullable Bundle savedInstanceState) {
    
        Button your_button = (Button) getActivity.findViewById(R.id.your_id_button)
    
        your_button.setOnClickListener(new OnClickListener() {
        public void onClick(View v)
        {
           button_parking();
        } 
        });
        return inflater.inflate(R.layout.fragment_select, null);
    
        }
    
        private void button_parking(){
        Intent myIntent = new Intent(getActivity(), parking.class);
        startActivity(myIntent);
    }
    

    }

    【讨论】:

      【解决方案2】:

      您尚未将视图绑定到您的片段,因此单击按钮无法工作。您需要将视图与findViewById() 绑定。通常您需要通过覆盖 onViewCreated() 来进行绑定,如下所示:

      public class select_fragment extends Fragment {
      
          @Nullable
          @Override
          public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
              return inflater.inflate(R.layout.fragment_select, null);
          }
      
          @Override
          public void onViewCreated(View view, Bundle savedInstanceState) {
              super.onViewCreated(view, savedInstanceState);
      
               // bind the view here.
               Button button = findViewById(R.id.your_button);
               button.setOnClickListener(new View.OnClickListener() {
                   public void onClick(View v) {
                       //call button method here
                       button_parking();
                   }
               });
          }
      
          private void button_parking() {
              Intent myIntent = new Intent(f, parking.class);
              startActivity(myIntent);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2021-05-23
        • 2016-08-26
        • 2012-02-23
        • 2011-04-28
        • 1970-01-01
        • 1970-01-01
        • 2021-01-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多