java – 一起使用Fragment和AppCompatActivity类
作者:互联网
嗨,我正在尝试创建一个使用两个不同类的应用程序,我知道我不能在Java中使用带有两个类的扩展.我如何将下面的代码分成两个不同的类,以便可以扩展Fragment和另一个AppCompatActivity?
package com.example.oliver.myapplication;
import android.support.v4.app.Fragment;
import android.app.AlertDialog;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.Random;
public class MyFragment extends AppCompatActivity, Fragment {
Button b, b2;
MediaPlayer nice, burp;
ImageButton img;
int n;
MediaPlayer [] s = new MediaPlayer[6];
AlertDialog.Builder adb;
public static MyFragment newInstance() {
MyFragment fragment = new MyFragment();
return fragment;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.my_fragment, container, false);
img = (ImageButton) rootView.findViewById(R.id.img);
s[0] = MediaPlayer.create(MyFragment.this, R.raw.burp);
s[1] = MediaPlayer.create(MyFragment.this, R.raw.robert);
s[2] = MediaPlayer.create(MyFragment.this, R.raw.burp2);
img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
for (int i = 0; i < 1; i++) {
Random r = new Random();
n = r.nextInt(3);
s[n].start();
}
}
});return rootView;
}}
解决方法:
上面的代码不是有效的Java.
一个类只能扩展一个类.您的活动/片段同时扩展了2个类.
上面给出的类是一个有效的Fragment子类,除了这些行:
s[0] = MediaPlayer.create(MyFragment.this, R.raw.burp);
s[1] = MediaPlayer.create(MyFragment.this, R.raw.robert);
s[2] = MediaPlayer.create(MyFragment.this, R.raw.burp2);
将“MyFragment.this”替换为“MyFragment.getActivity()”.
现在你可以用“extends Fragment”替换“extends AppCompatActivity,Fragment”
现在你有一个有效的片段.
自己创建AppCompatActivity.查找如何将片段添加到活动中.
作为良好编程实践的一个提示,我建议您将onCreateView()中的以下代码移动到onActivityCreated():
img = (ImageButton) rootView.findViewById(R.id.img);
s[0] = MediaPlayer.create(MyFragment.this, R.raw.burp);
s[1] = MediaPlayer.create(MyFragment.this, R.raw.robert);
s[2] = MediaPlayer.create(MyFragment.this, R.raw.burp2);
img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
for (int i = 0; i < 1; i++) {
Random r = new Random();
n = r.nextInt(3);
s[n].start();
}
}
});
更改
img = (ImageButton) rootView.findViewById(R.id.img);
至
img = (ImageButton) getView().findViewById(R.id.img);
标签:java,android,android-studio,android-fragments,appcompatactivity 来源: https://codeday.me/bug/20190608/1200337.html