public class MainActivity extends AppCompatActivity implements
TopSectionFragment.TopSectionListener {
当我尝试实现TopSectionFragment
时,写入变为红色,然后当我的鼠标移过它时它会显示Cannot resolve symbol
。
这一切都发生在Android Studio中。
我的MainActivity.java看起来像这样:
package com.example.danielhunter.fragments;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;`
public class MainActivity extends AppCompatActivity
implements TopSectionFragment.TopSectionListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
我的TopSectionFragment.java看起来很喜欢这个:
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.ViewGroup;
import android.view.View;
import android.view.LayoutInflater;
import android.support.v4.app.Fragment;
import android.widget.Button;
import android.widget.EditText;
import android.app.Activity;
import com.example.danielhunter.fragments.R;
public class TopSectionFragment extends Fragment {
private static EditText topTextInput;
private static EditText bottomTextInput;
TopSectionListener activityCommander;
public interface TopSectionListener{
public void createMeme(String top,String bottom);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try{
activityCommander = (TopSectionListener) activity;
}catch (ClassCastException e){
throw new ClassCastException(activity.toString());
}
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.top_section_fragment, container, false);
topTextInput = (EditText) view.findViewById(R.id.topTextInput);
bottomTextInput = (EditText) view.findViewById(R.id.bottomTextInput);
final Button button = (Button) view.findViewById(R.id.button);
button.setOnClickListener(
new View.OnClickListener(){
public void onClick(View v){
buttonClicked(v);
}
}
);
return view;
}
// calls this when the button is clicked
public void buttonClicked(View view){
activityCommander.createMeme(topTextInput.getText().toString(), bottomTextInput.getText().toString());
}
}
答案 0 :(得分:0)
为了使类正确实现接口,它必须包含接口中定义的所有方法的实现。在您的情况下,MainActivity需要一个带有签名void createMeme(String top,String bottom)
的方法才能进行编译。