вот большое дело. У меня есть проект андроида, который имеет несколько видов деятельности с различными пакетами, некоторые виды деятельности имеют представление списка с пользовательским адаптером с кнопкой и счетчиком. так же как и у других видов деятельности, есть вид списка, но другой виджет. например. Представление списка сотрудников с настраиваемым адаптером, в котором при нажатии кнопки в виде списка будет отображаться информация о сотруднике (Activity) и вид списка учеников при щелчке на кнопке, отображает детальность ученика (Activity). перенаправление деятельности производится в пользовательском адаптере. У некоторой активности есть только просмотр, по которому нажата другая активность.базовый класс для диспетчера фрагментов андроида
Я хочу преобразовать их в фрагмент. Я знаю, что интерфейсы и обратный фрагмент к активности и активности заменит фрагмент.
Мне просто нужна логика, как я могу управлять целым обменом фрагментами. вместо использования количества интерфейсов и обратного вызова. вот ссылка Android managing fragments from activity elegantly ответил Alireza, что я изучал. он может сделать обмен фрагментами централизованными, но для каждого события кнопки списка списка потребуется много условий, щелкнув фрагмент или простую кнопку в фрагменте, чтобы заменить фрагмент.
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;
}
}
}
Пожалуйста, внесите свой код. Что бы вы ни делали до сих пор. – Karthikeyan
в адаптере на кнопке, как я могу заменить фрагмент фрагментом подробного представления, если все это вид списка внутри фрагмента. –