【问题标题】:onLongClickListener in layout with tabs带有选项卡的布局中的 onLongClickListener
【发布时间】:2015-10-31 20:31:08
【问题描述】:

我按照本教程:http://www.android4devs.com/2015/01/how-to-make-material-design-sliding-tabs.html?m=1 制作了一个包含 5 个选项卡的布局。现在我想在第一个选项卡中为按钮放置一个 OnLongClickListener 以使其共享 sound1。我在 MainActivity.java 中添加了这段代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button1 = (Button) findViewById(R.id.button1);

    button1.setLongClickable(true);
    button1.setOnLongClickListener(new View.OnLongClickListener() {

        @Override
        public boolean onLongClick(View arg0) {
            Intent share = new Intent(Intent.ACTION_SEND);
            share.setType("audio/ogg");

            Uri uri = Uri.parse("android.resource://" + getPackageName()
                    + "/raw/" + R.raw.sound1);
            share.putExtra(Intent.EXTRA_STREAM, uri);
            startActivity(Intent.createChooser(share, "Share Sound File"));

            return true;
        }

    });

但这会导致它在启动时崩溃,并且 logcat 会这样说:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setLongClickable(boolean)' on a null object reference

【问题讨论】:

  • “activity_main”布局是否有 id 为“button1”的按钮?
  • 使用类 onLongClick 方法更改视图从 new View.onLongClickListener 到这可能会解决它
  • 达瓦尔:呃……没有。 id 为 button1 的按钮位于 tab_1 布局中。我对 android 很陌生,但这只是我犯的一个愚蠢的错误:P 但我不能只将 onCreate 粘贴到 Tab1.java 文件中。我需要什么代码才能让它在 Tab1.java 中工作?

标签: android share onlongclicklistener


【解决方案1】:

您正在使用片段。您应该在 FragmentonCreateView()onViewCreated() 回调中执行此操作

public class Tab1 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v =inflater.inflate(R.layout.tab_1,container,false);
        button1 = (Button) v.findViewById(R.id.button1);
        button1.setLongClickable(true);
        ...
        return v;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多