这是一个大问题。我有android项目,它有多个不同包的活动, 某些活动具有带有按钮和微调器的自定义适配器的列表视图。同样的其他活动有列表视图但不同的小部件。 例如。具有自定义适配器的员工列表视图,其中按钮单击列表视图将显示员工详细信息(活动),按钮单击时的学生列表视图将显示学生详细信息(活动)。 活动的重定向在自定义适配器中进行。 某些活动仅包含查看其他活动是否已打开的视图。
我想将它们转换为片段。我知道接口和回调片段到活动和活动将替换片段。
我只需要逻辑如何管理片段的整个交换。而不是使用多个接口和回调。 这是我研究过的Alireza回答的链接Android managing fragments from activity elegantly。它可以使我的片段交换集中,但是在列表适配器按钮的每个事件上需要很多条件点击片段或片段中的简单按钮来替换片段。
public class List extends AppCompatActivity implements AsyncRequest.OnAsyncRequestComplete {
private boolean boolScroll = true;
private int incre = 1;
private ListAdapter adapter;
private EditText txtNoticeSearch;
private ListView listView;
private Button btnSearch;
private Button btnClear;
private View footer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notice_activity);
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
android.support.v7.app.ActionBar ab = getSupportActionBar();
if (ab != null) ab.setDisplayHomeAsUpEnabled(true);
StrictMode.ThreadPolicy policy;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
findViewByID();
listView.setOnScrollListener(onScrollListener());
btnClear.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
incre = 1;
boolScroll = true;
txtNoticeSearch.setText(null);
if (adapter != null)
adapter.clear();
search(true);
}
});
btnSearch.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String std = txtNoticeSearch.getText().toString();
if (std.trim().length() > 1) {
incre = 1;
boolScroll = true;
if (adapter != null)
adapter.clear();
try {
InputMethodManager imm = (InputMethodManager) getSystemService
(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(new View(List.this).getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
} catch (Exception e) {
// TODO: handle exception
}
search(false);
} else
Toast.makeText(getApplicationContext(),
"Please enter atleast two character.", Toast.LENGTH_LONG)
.show();
}
});
txtNoticeSearch.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
listView.setVisibility(View.GONE);
incre = 1;
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
search(true);
}
private AbsListView.OnScrollListener onScrollListener() {
return new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int threshold = 5;
int count = listView.getCount();
if (scrollState == SCROLL_STATE_IDLE) {
if (listView.getLastVisiblePosition() >= count - threshold) {
if (boolScroll) {
if (txtNoticeSearch.getText().toString().trim().length() > 0)
search(false);
else
search(true);
}
}
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
}
};
}
private void findViewByID() {
txtNoticeSearch = (EditText) findViewById(R.id.txtNoticeSearch);
btnSearch = (Button) findViewById(R.id.btnSearch);
listView = (ListView) findViewById(R.id.listViewNotice);
btnClear = (Button) findViewById(R.id.btnClear);
footer = ((LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.listview_loading_footer, listView, false);
}
private void search(boolean bool) {
if (listView.getFooterViewsCount() == 0)
listView.addFooterView(footer);
String URL;
if (bool) {
URL = new SqLite(getApplicationContext()).returnDefaultURI() + "notice/0/" + incre;
incre = incre + 1;
} else {
URL = new SqLite(getApplicationContext()).returnDefaultURI() + "notice/" +
txtNoticeSearch.getText().toString().trim() + "/" + incre;
incre = incre + 1;
}
AsyncRequest asyncRequest;
if (incre > 2)
asyncRequest = new AsyncRequest(List.this, "GET", null, null, 1);
else
asyncRequest = new AsyncRequest(List.this, "GET", null, "Fetching data", 1);
asyncRequest.execute(URL);
}
@Override
public void asyncResponse(String response, int apiKey) {
if (response != null)
if (response.trim().equalsIgnoreCase("{\"Message\":\"Session Expired !\"}"))
new AppUtility(List.this).sessionExpiresState(List.this);
else
switch (apiKey) {
case 1:
if (listView.getFooterViewsCount() > 0)
if (listView.getAdapter() != null)
listView.removeFooterView(footer);
fillListView(response);
break;
case 2:
openFile(response);
break;
}
}
private void fillListView(String response) {
try {
ArrayList<ListRowItem> lstItem;
if (listView.getCount() == 0) {
Type listType = new TypeToken<ArrayList<ListRowItem>>() {
}.getType();
lstItem = new Gson().fromJson(response, listType);
adapter = new ListAdapter(List.this, lstItem);
listView.setAdapter(adapter);
} else {
Type listType = new TypeToken<ArrayList<ListRowItem>>() {
}.getType();
lstItem = new Gson().fromJson(response, listType);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
adapter.addAll(lstItem);
} else {
for (ListRowItem items : lstItem) {
adapter.add(items);
}
}
}
adapter.setNotifyOnChange(true);
listView.setVisibility(View.VISIBLE);
} catch (Exception e) {
// TODO: handle exception
if (response.contains("{\"Message\":\"Data not found !\"}")) {
if (incre == 2) {
Toast.makeText(getApplicationContext(), "Data not found", Toast.LENGTH_LONG)
.show();
boolScroll = false;
} else
boolScroll = false;
}
}
}
class ListAdapter extends ArrayAdapter<ListRowItem> {
private final Context context;
public ListAdapter(Context asyncTask, java.util.List<ListRowItem> items) {
super(asyncTask, R.layout.notice_listitem, items);
this.context = asyncTask;
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
final ListRowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.notice_listitem, parent, false);
holder = new ViewHolder();
holder.txtSno = (TextView) convertView.findViewById(R.id.txtSno);
holder.txtNoticePublishDate = (TextView) convertView.findViewById(R.id
.txtNoticePublishDate);
holder.btnView = (Button) convertView.findViewById(R.id.btnView);
holder.txtNoticeDescription = (TextView) convertView.findViewById(R.id
.txtNoticeDescription);
holder.txtNoticeName = (TextView) convertView.findViewById(R.id.txtNoticeName);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtSno.setText(String.valueOf(position + 1));
holder.txtNoticeDescription.setText(new AppUtility().TitleCase(rowItem.getDescription
()));
holder.txtNoticeName.setText(new AppUtility().TitleCase(rowItem.getFileTitle()));
try {
holder.txtNoticePublishDate.setText(String.valueOf((new SimpleDateFormat("dd MMM " +
"yyyy HH:mm:ss", Locale.US)).format((new SimpleDateFormat
("yyyy-MM-dd'T'HH:mm:ss", Locale.US)).parse(rowItem.getUpdateDate()))));
} catch (ParseException e) {
holder.txtNoticePublishDate.setText(new AppUtility().TitleCase(rowItem
.getUpdateDate()));
}
// here i want to replace fragment by calling back to fragment and
// then activity to call replace fragment
holder.btnView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
DownloadFile downloadFile = new DownloadFile();
downloadFile.setName(rowItem.getFileTitle());
downloadFile.setExtension(rowItem.getContentType().split("/")[1]);
downloadFile.setDownloadUrl(new SqLite(context).returnDefaultURI() +
"notice/" + rowItem.getDocumentUploadID());
downloadFile.setFolderName(context.getResources().getString(R.string
.folder_name));
downloadFile.setMessage();
AsyncRequest asyncRequest = new AsyncRequest(context, downloadFile, 2);
asyncRequest.execute(downloadFile.getDownloadUrl());
}
});
return convertView;
}
/*private view holder class*/
private class ViewHolder {
TextView txtSno;
TextView txtNoticeName;
TextView txtNoticeDescription;
TextView txtNoticePublishDate;
Button btnView;
}
}
class ListRowItem {
private final String FileTitle;
private final String Description;
private final String ContentType;
private final int DocumentUploadID;
private final String UpdateDate;
ListRowItem() {
this.FileTitle = "";
this.Description = "";
this.ContentType = "";
this.DocumentUploadID = 0;
this.UpdateDate = "";
}
public String getFileTitle() {
return FileTitle;
}
public int getDocumentUploadID() {
return DocumentUploadID;
}
public String getUpdateDate() {
return UpdateDate;
}
public String getDescription() {
return Description;
}
public String getContentType() {
return ContentType;
}
}
}
答案 0 :(得分:0)
有很多方法可以做到。
方法1: 将FragmentManager传递给适配器构造函数并替换您想要的片段。
方法2: 第1步:创建一个界面
public interface FragmentChange {
void changeFragment(Fragment fragment);
}
第2步:创建BaseActivity,其他活动将继承它
步骤3:在BaseActivity中实现FragmentChange并为changeFragment方法添加函数以更改片段。
步骤4:onAttach(活动活动)将活动转换为BaseActivity并传递给适配器的构造函数。并在点击按钮时调用该界面的方法。