【发布时间】:2017-09-10 23:41:25
【问题描述】:
我尝试在 Fragment 中实现 getIntent(); 并显示文本,但我得到了 Cannot resolve method 'getIntent()'
这是 Fragment3.java 的一部分
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_3, container, false);
TextView textViewDisplayResult = (TextView) getView().findViewById(R.id.text_view_display_result);
textViewDisplayResult.setText(getIntent().getBooleanExtra("KEY_ANSWER", false)?R.string.Good_answer:R.string.Wrong_answer);
这是用于显示文本的 xml TextView
<TextView
android:id="@+id/text_view_display_result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"/>
和 MainActivity 的一部分关于这个问题
final Intent intent = new Intent(MainActivity.this, Fragment3.class);
buttonCheckAnswer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (checkAnswers())
intent.putExtra("Key Answer", true);
else
intent.putExtra("Key Answer", false);
startActivity(intent);
}
});
这是整个 Fragment3
package make.appaplication;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* A simple {@link Fragment} subclass.
*/
public class Fragment41 extends Fragment {
public Fragment41() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_3, container, false);
TextView textViewDisplayResult = (TextView) getView().findViewById(R.id.text_view_display_result);
textViewDisplayResult.setText(getActivity().getIntent().getBooleanExtra("KEY_ANSWER", false)?R.string.Good_answer:R.string.Wrong_answer);
}
}
【问题讨论】:
-
将 onCreateView 方法更改为:@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // 为这个片段膨胀布局 View v = inflater.inflate(R.layout.fragment_3,容器,假); TextView textViewDisplayResult = (TextView) v.findViewById(R.id.text_view_display_result); textViewDisplayResult.setText(getActivity().getIntent().getBooleanExtra("KEY_ANSWER", false)?R.string.Good_answer:R.string.Wrong_answer);返回 v; }
-
即确保在方法结束时调用运算符“return”
-
仍将
getBooleanExtra设为Cannot resolve method 'getBooleanExtra(java.lang.String, boolean)。也许是因为还有"KEY_ANSWER",true没有添加到最后一行? -
能否更新您的代码
-
我按照你建议的 Serg 做了,正如我所说的,仍然会在
getBooleanExtra上抛出错误:(
标签: java android android-intent