我是编程的新手,并一直在尝试为学校项目的Fragment添加列表视图+ arrayadapter。提到这个问题却无济于事。 https://stackoverflow.com/questions/32350275/no-suitable-constructor-found-for-arrayadaptermainlistactivity-getblogpoststask#=
package com.tabian.tabfragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import android.widget.Button;
public class Tab1Fragment extends Fragment {
private static final String TAG = "Tab1Fragment";
private ListView listOfLeagues;
final ArrayList<String> listItems = new ArrayList<String>();
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab1_fragment,container,false);
listOfLeagues = (ListView) view.findViewById(R.id.listOfLeagues);
String[] values = new String[] { "World Cup", "Champions League" };
for(int i = 0; i < values.length; i++){
listItems.add(values[i]);
}
ArrayAdapter adapter = new ArrayAdapter<(Tab1Fragment.this,
android.R.layout.simple_list_item_1, listItems);
listOfLeagues.setAdapter(adapter);
listOfLeagues.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedLeague = listItems.get(position).toString();
Intent titleIntent = new Intent(view.getContext(), abc.class);
titleIntent.putExtra("league", selectedLeague);
startActivity(titleIntent);
}
});
return view;
}
}
最佳答案
ArrayAdapter
构造函数的第一个参数应该是Context
,但是您要传递Fragment
,即Tab1Fragment.this
。
在处于生命周期中处于连接状态的Fragment
中,可以使用Context
获取getContext()
。因此,将Tab1Fragment.this
替换为getContext()
。