gpt4 book ai didi

android - getApplicationContext() 错误安卓

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:46:29 26 4
gpt4 key购买 nike

我有一个 fragment ,允许用户输入消息和消息将被传递到的电话号码。我收到错误消息“无法解析方法 getApplicationContext()” 我在这里查看了答案 the method getApplicationContext() is undefined但这对我没有帮助,也许我实现错误但我不确定!此代码作为 Activity 正常运行,但作为 fragment 运行不佳。

FragmentTab1 类

package com.androidbegin.absfragtabhost;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.app.Fragment;
import android.app.Activity;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class FragmentTab3 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragmenttab3, container, false);
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);

sendBtn = (Button) rootView.findViewById(R.id.btnSendSMS);
txtphoneNo = (EditText) rootView.findViewById(R.id.editTextPhoneNo);
txtMessage = (EditText) rootView.findViewById(R.id.editTextSMS);

sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendSMSMessage();
}
});

return rootView;
}



Button sendBtn;
EditText txtphoneNo;
EditText txtMessage;



protected void sendSMSMessage() {
Log.i("Send SMS", "");

String phoneNo = txtphoneNo.getText().toString();
String message = txtMessage.getText().toString();

try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS failed, please try again.",
Toast.LENGTH_LONG).show();
e.printStackTrace();


}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}


}

最佳答案

方法 getApplicationContext() 在类 Fragment 中不存在。但是,它确实存在于 Activity 类中,因此您可以使用 getActivity().getApplicationContext() 从 fragment 对象中获取上下文。 (假设 fragment 附加到一个 Activity ,所以 getActivity() 将返回一个非空对象,这通常是正确的)

关于android - getApplicationContext() 错误安卓,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28562595/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com