带有选项卡的布局中的 onLongClickListener
onLongClickListener in layout with tabs
我按照本教程进行操作: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
您正在使用片段。您应该在 Fragment's onCreateView() or 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;
}
}
我按照本教程进行操作: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
您正在使用片段。您应该在 Fragment's onCreateView() or 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;
}
}