我创建了一个标签布局。我想创建一个可调用的数字,我必须定义onCLickListener
,请参阅下面Tab2
中编写的代码:
在这个错误中显示MainActivity.this
不是一个封闭的类,那么我应该写什么呢? (tab2.xml
是Tab的布局文件的名称)
package com.firstapp.admin.herbalteaco;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
/**
* Created by admin on 11/25/2017.
*/
public class Tab2 extends Fragment implements View.OnClickListener{
private TextView tvCall;
private Button btnLogin;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab2 , container , false);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
btnLogin = (Button) btnLogin.findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(this);
tvCall = (TextView) tvCall.findViewById(R.id.tvCall);
tvCall.setOnClickListener((new View.OnClickListener() {
public void onClick(View arg0) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:+91999999999"));;
if (ActivityCompat.checkSelfPermission( MainActivity.this,
Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
return;
}
startActivity(callIntent);
}
}));
}
答案 0 :(得分:0)
尝试以下代码
定义Global vairable,如下所示
int REQUEST_CALL=101;
请求权限,如下所示
if (ActivityCompat.checkSelfPermission(getContext(),
android.Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(),
new String[]{android.Manifest.permission.CALL_PHONE},
REQUEST_CALL);
} else {
Log.e("DB", "PERMISSION GRANTED");
// do your call
}
请勿忘记处理如下所示的请求权限
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
if(requestCode == REQUEST_CALL){
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// Call task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
}
}
答案 1 :(得分:0)
您可以在扩展logger.info( " key :value {}" + e.getKey(), e.getValue());
or
logger.info( " key :value {} {}" , e.getKey() , e.getValue());
的类中调用getActivity()
。这将为您提供拥有该片段的Fragment
实例。由于Activity
是Activity
的子类,因此您可以在需要Context
的任何位置使用此实例。