【问题标题】:how to add a working button in a fragment? [duplicate]如何在片段中添加工作按钮? [复制]
【发布时间】:2017-05-05 23:17:30
【问题描述】:

您好,我是 Android 工作室的新手,并试图让一个按钮在片段中工作,但它不起作用?

我的片段代码:

package layout;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SearchViewCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;   
import com.marcphi.csgoskin.R;
import com.marcphi.csgoskin.SkinListActivity;

public class NewsFragment extends Fragment implements View.OnClickListener {

    View view;
    Button btn;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_news, container, false);  
        btn = (Button) view.findViewById(R.id.button1);
        btn.setOnClickListener(this);         
        return  view;
    }
    public void onClick(View view){
        Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show();
        Intent intent = new Intent(getActivity(), SkinListActivity.class);
        startActivity(intent);  
    }       
}

现在调试时出现错误。

【问题讨论】:

  • 贴出完整代码或者google ,在fragment中设置setOnClickListener
  • 你的片段类应该实现 OnClickListener
  • “不工作”不是错误。发布代码或解释得更好。
  • @PavneetSingh 完成

标签: java android


【解决方案1】:

一种方法:

btn = (Button) view.findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // Perform action on click   

                Snackbar.make(v, 
                              "Replace with your own action", 
                               Snackbar.LENGTH_LONG)
                         .setAction("Action", null).show();

                Intent intent = new Intent(getActivity(),
                                           SkinListActivity.class);
                startActivity(intent);  
            }
        });

【讨论】:

    【解决方案2】:

    在你的 onClick 方法中添加:

    If (view.getId() == R.id.button1) {
       // Here place code of onClick method
    }
    

    【讨论】:

      【解决方案3】:

      它不起作用,因为Snackbar.make() 将 coordinatorLayout 作为第一个参数,并且您在其中传递按钮。

      如果你想使用 Snackbar,你必须在片段中使用 CoordinatorLayout 作为你的 rootView,然后像这样将它传递给 Snackbar:

      Snackbar.make(coordinatorLayout, "Replace with your own action", Snackbar.LENGTH_LONG)
                  .setAction("Action", null).show();
      

      【讨论】:

        猜你喜欢
        • 2016-11-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-22
        • 1970-01-01
        相关资源
        最近更新 更多