显示功能位于Main_activity类下。它显示给定目录下的所有文件。它来自
protected void OnCreate(Bundle SavedInstanceState)
{
..//other code
display(path)
}
public void display(String path)
{
try {
File folderX = new File(path);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle(folderX.getParentFile().getName() + " / " + folderX.getName());
final File[] folderXCHILD = folderX.listFiles();
Arrays.sort(folderXCHILD, new FileComparator());
GridView gridView = (GridView)findViewById(R.id.gridView);
gridAdapter = new GridAdapter(this, folderXCHILD,isShow);
gridView.setAdapter(gridAdapter);
}
catch (Exception e)
{
Toast.makeText(this, "Cannot display the Content.", Toast.LENGTH_SHORT).show();
}
}
现在,我有另一个名为GridAdapter的类,它在网格中显示内容。 GridAdapter类本身不是Activity。
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final Holder holder = new Holder();
View rowView;
if (convertView == null) {
rowView = inflater.inflate(R.layout.gridout, parent, false);
} else {
rowView = convertView;
}
holder.tv = (TextView) rowView.findViewById(R.id.textView1);
holder.img = (ImageView) rowView.findViewById(R.id.imageView1);
holder.chk = (CheckBox) rowView.findViewById(R.id.checkBox);
if (isShow) {
holder.chk.setVisibility(View.VISIBLE);
} else {
holder.chk.setVisibility(View.GONE);
}
final File f = data[position];
if (f.isDirectory())
{
holder.img.setImageResource(R.mipmap.folderpic);
holder.tv.setText(f.getName());
holder.chk.setChecked(checkBoxState[position]);
}
else
{
ImageLoader.getInstance().displayImage("file://" + f.getPath(), holder.img);
holder.tv.setBackgroundResource(R.color.colorSecond);
holder.tv.setText("");
holder.chk.setChecked(checkBoxState[position]);
}
rowView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(f.isDirectory())
{
// I want to call the display(f.getPath()) method of MainActivity.
}
});
return rowView;
}
问题是我想从GridAdapter中的onClick()方法调用display()方法。我该怎么办?
答案 0 :(得分:0)
你必须选择: 1.将上下文转换为活动 2.将上下文强制转换为接口
看看这一行:
gridAdapter = new GridAdapter(this, folderXCHILD,isShow);
您正在向适配器发送上下文。因此,在适配器内部保存上下文的引用并使用它
((YourActivityOrInterface)context).YourFunctionOnActivity()