gpt4 book ai didi

java - Android fragment 和 baseadapter 之间的通信

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:13:34 25 4
gpt4 key购买 nike

需要专家意见我应该如何组织这个问题。我有一个驻留在 fragment 中的自定义方法 process_filter,因为它需要访问该 fragment 的私有(private) TextViewList

在处理过程中,这个 fragment 会访问一个BaseAdapter,在这个BaseAdapter里面我需要使用back process_filter方法

基本结构如下:

MyFragment.java

public class MyFragment extends Fragment {

private List<String> filter_list;
private TextView no_of_filter;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

View view = inflater.inflate(R.layout.my_fragment_layout, container, false);
no_of_filter = (TextView) view.findViewById(R.id.no_of_filter_tv);
.
MyAdapter custom_adapter = new MyAdapter(context, "string 1", "string 2");
.
process_filter("string 1", "string 2");
.
}

public void process_filter(String in_preference, String current_value)
{
no_of_filter.setText(in_preference);
}

MyAdapter.java

   class MyAdapter extends BaseAdapter {

public View getView( final int position, View convertView, ViewGroup parent)
{
holder.checkBox.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
//Here I need to access back process_filter from fragment
process_filter ("string 1, string 2");
}
}
}
}

最佳答案

创建一个从适配器到 fragment 的接口(interface)。

在您的适配器中创建接口(interface)并将其传递给您的适配器的构造函数

class MyAdapter extends BaseAdapter {

public interface IProcessFilter {
void onProcessFilter(String string1, String string2)
}

private IProcessFilter mCallback;

public MyAdapter(Context context, String string1, String string2, IProcessFilter callback) {
mCallback = callback;
}

public View getView( final int position, View convertView, ViewGroup parent)
{
holder.checkBox.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
mCallback.onProcessFilter("string1", "string2");
}
}
}
}

最后,像这样在你的 fragment 中实现它

public class MyFragment extends Fragment implements IProcessFilter {
...
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

View view = inflater.inflate(R.layout.my_fragment_layout, container, false);
no_of_filter = (TextView) view.findViewById(R.id.no_of_filter_tv);

MyAdapter custom_adapter = new MyAdapter(context, "string 1", "string 2", this);
}

@Override
public void onProcessFilter(String string1, String string2) {
// Process the filter
}
}

关于java - Android fragment 和 baseadapter 之间的通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32880248/

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