适配器项目单击“从片段”
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了适配器项目单击“从片段”相关的知识,希望对你有一定的参考价值。
我在My Fragment中有ListView。我的列表项中有一些操作按钮。我的适配器如下所示
public class StatAdapter extends BaseAdapter {
private Activity mActivity;
private ArrayList<Stat> mData;
private LayoutInflater mInflater;
private Drawable drawableOffline,drawableOnline;
public StatAdapter(Activity activity, ArrayList<Stat> data) {
mActivity = activity;
mData = new ArrayList<>();
mData.addAll(data);
mInflater = (LayoutInflater) mActivity.getSystemService(AppCompatActivity.LAYOUT_INFLATER_SERVICE);
drawableOnline = activity.getResources().getDrawable(R.drawable.round_online);
drawableOffline = activity.getResources().getDrawable(R.drawable.round_offline);
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int pPosition, View pView, ViewGroup pParent) {
pView = mInflater.inflate(R.layout.list_stat, null,false);
String name = mData.get(pPosition).getName();
String first = name.substring(0, 1);
TextView txtCount = pView.findViewById(R.id.txt_count);
txtCount.setText(first);
TextView txtName = pView.findViewById(R.id.txt_name);
txtName.setText(name);
TextView txtNumber = pView.findViewById(R.id.txt_number);
txtNumber.setText("Number: "+mData.get(pPosition).getNumber());
int onlineBg = ResourcesCompat.getColor(mActivity.getResources(), R.color.onlineBg, null);
int offlineBg = ResourcesCompat.getColor(mActivity.getResources(), R.color.offlineBg, null);
int white = ResourcesCompat.getColor(mActivity.getResources(), R.color.colorWhite, null);
int black = ResourcesCompat.getColor(mActivity.getResources(), R.color.colorBlack, null);
ImageView btnGetCSV = pView.findViewById(R.id.btnGetCSV);
ImageView btnNotificationOff = pView.findViewById(R.id.btnNotificationOff);
ImageView btnNotificationOn = pView.findViewById(R.id.btnNotificationOn);
ImageView btnNumberDetails = pView.findViewById(R.id.btnNumberDetails);
ImageView btnRemoveNumber = pView.findViewById(R.id.btnRemoveNumber);
btnGetCSV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(mActivity, "Get CSV", Toast.LENGTH_SHORT).show();
}
});
btnNotificationOff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(mActivity, "Notification Off", Toast.LENGTH_SHORT).show();
}
});
btnNotificationOn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(mActivity, "Notification On", Toast.LENGTH_SHORT).show();
}
});
btnNumberDetails.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(mActivity, "Number Details", Toast.LENGTH_SHORT).show();
}
});
btnRemoveNumber.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(mActivity, "Remove Number", Toast.LENGTH_SHORT).show();
}
});
TextView txtSatus = pView.findViewById(R.id.txt_status);
txtSatus.setText(mData.get(pPosition).isOnline() ? "Online" : "Offline");
if(mData.get(pPosition).isOnline()){
txtCount.setCompoundDrawablesWithIntrinsicBounds(drawableOnline,null,null,null);
}else{
txtCount.setCompoundDrawablesWithIntrinsicBounds(drawableOffline,null,null,null);
}
txtCount.setTextColor(mData.get(pPosition).isOnline() ? white : black);
txtCount.setBackgroundColor(mData.get(pPosition).isOnline() ? onlineBg : offlineBg);
TextView txtTime = pView.findViewById(R.id.txt_time);
txtTime.setText("Since " + mData.get(pPosition).getLastOnline());
return pView;
}
public void setData(ArrayList<Stat> data) {
mData.clear();
mData.addAll(data);
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
notifyDataSetChanged();
}
});
}
public void addData(Stat data) {
mData.add(data);
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
notifyDataSetChanged();
}
});
}
public void clearData() {
mData.clear();
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
notifyDataSetChanged();
}
});
}
public Stat getStat(int position) {
return mData.get(position);
}
}
而我的片段如下
public class StateFragment extends Fragment {
private final int PERMISSION_CONTACT = 10003;
private final int PICK_CONTACT = 10;
@BindView(R.id.list_stats)
ListView mStatList;
@BindView(R.id.swipe_refresh)
SwipeRefreshLayout swipeRefresh;
EditText edtName, edtNumber;
private Activity mActivity;
private StatAdapter mAdapter;
private Dialog mWaitDialog;
ApiInterface apiService;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_stats, container, false);
mActivity = getActivity();
apiService = ApiUtils.getAPIService(getContext());
ButterKnife.bind(this, view);
NumberData.getInstance();
mAdapter = new StatAdapter(mActivity, NumberData.getInstance().mData);
mStatList.setAdapter(mAdapter);
mStatList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Stat stat = mAdapter.getStat(position);
Intent intent = new Intent(mActivity, DetailLogActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable(DetailLogActivity.DATA_OBJ, stat);
bundle.putInt("position", position);
intent.putExtras(bundle);
startActivity(intent);
}
});
swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
refreshData();
}
});
mWaitDialog = new Dialog(mActivity);
mWaitDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mWaitDialog.setContentView(R.layout.dialog_wait);
if (mWaitDialog.getWindow() != null) {
mWaitDialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
}
mWaitDialog.setCancelable(false);
return view;
}
private void contact_permission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (mActivity.checkSelfPermission(android.Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
AlertManager.createSingleCallbackAlert(mActivity, "We Need Your Permission",
"Please Grant Permission to Read Contacts to Access Number.", false, "OK",
new DialogInterface.OnClickListener() {
@TargetApi(23)
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
requestPermissions(new String[]{android.Manifest.permission.READ_CONTACTS}, PERMISSION_CONTACT);
}
});
} else
getContact();
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_stats,menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.actionCompare){
compare();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
@TargetApi(Build.VERSION_CODES.M)
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSION_CONTACT: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getContact();
} else {
Toast.makeText(mActivity.getApplicationContext(), "You Can Not Load Number from Contact", Toast.LENGTH_SHORT).show();
}
}
}
}
private void getContact() {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
private void refreshData() {
NumberData.getInstance().mData.clear();
mAdapter.clearData();
apiService.getNumbers(NumberData.getInstance().mUserEmail).enqueue(new retrofit2.Callback<GetNumberCallback>() {
@Override
public void onResponse(retrofit2.Call<GetNumberCallback> call, retrofit2.Response<GetNumberCallback> response) {
try {
GetNumberCallback numberCallback = response.body();
if (numberCallback.getCode() == 1) {
for (int i = 0; i < numberCallback.getNumber().size(); i++) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
Date mDate = sdf.parse(numberCallback.getLastOnline().get(i));
long lastOnlineTime = mDate.getTime();
NumberData.getInstance().mData.add(new Stat(numberCallback.getName().get(i), numberCallback.getNumber().get(i),
numberCallback.getStatus().get(i)==1, formatDate(lastOnlineTime)));
}
mAdapter.setData(NumberData.getInstance().mData);
} else {
AlertManager.createSingleCallbackAlert(mActivity, "Error", "Server Problem",
false, "Retry", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
} catch (Exception pE) {
}
if (swipeRefresh.isRefreshing()) {
mActivity.runOnUiThread((new Runnable() {
@Override
public void run() {
swipeRefresh.setRefreshing(false);
}
}));
}
}
@Override
public void onFailure(retrofit2.Call<GetNumberCallback> call, Throwable t) {
call.cancel();
AlertManager.createSingleCallbackAlert(mActivity, "Unknown Error",
"Error reaching server", false, "OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
if (swipeRefresh.isRefreshing()) {
mActivity.runOnUiThread((new Runnable() {
@Override
public void run() {
swipeRefresh.setRefreshing(false);
}
}));
}
}
});
}
@Override
public void onResume() {
if (mAdapter != null) {
//mAdapter.setData(NumberData.getInstance().mData);
refreshData();
}
super.onResume();
}
@Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (PICK_CONTACT):
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = mActivity.managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone.equalsIgnoreCase("1")) {
Cursor phones = mActivity.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id,
null, null);
assert phones != null;
phones.moveToFirst();
edtNumber.setText(phones.getString(phones.getColumnIndex("data1")));
phones.close();
}
edtName.setText(c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
}
}
break;
}
}
private String getDateTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd MMM, HH:mm:ss", Locale.US);
Date date = new Date();
return dateFormat.format(date);
}
private String formatDate(long time) {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd MMM, HH:mm:ss ", Locale.US);
Date date = new Date(time);
return dateFormat.format(date);
}
}
你可以看到我的适配器中有一些动作按钮btnGetCSV
等,我可以在其中实现onclick但很难在适配器中实现某些功能,所以我想从Fragment中做到这一点。我是android的新手,不知道我怎么能从片段中做到这一点。让我知道是否有人可以举例说明这样做。谢谢
答案
你需要像这样使用适配器中的回调方法创建接口“OnMenuItemClickListener”。
public class StatAdapter extends BaseAdapter {
private Activity mActivity;
private ArrayList<Stat> mData;
private LayoutInflater mInflater;
private Drawable drawableOffline,drawableOnline;
private OnMenuItemClickListener onMenuItemClickListener;
public StatAdapter(Activity activity, ArrayList<Stat> data,OnMenuItemClickListener onMenuItemClickListener) {
mActivity = activity;
mData = new ArrayList<>();
mData.addAll(data);
this.onMenuItemClickListener = onMenuItemClickListener;
mInflater = (LayoutInflater) mActivity.getSystemService(AppCompatActivity.LAYOUT_INFLATER_SERVICE);
drawableOnline = activity.getResources().getDrawable(R.drawable.round_online);
drawableOffline = activity.getResources().getDrawable(R.drawable.round_offline);
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int pPosition, View pView, ViewGroup pParent) {
pView = mInflater.inflate(R.layout.list_stat, null,false);
String name = mData.get(pPosition).getName();
String first = name.substring(0, 1);
TextView txtCount = pView.findViewById(R.id.txt_count);
txtCount.setText(first);
TextView txtName = pView.findViewById(R.id.txt_name);
txtName.setText(name);
TextView txtNumber = pView.findViewById(R.id.txt_number);
txtNumber.setText("Number: "+mData.get(pPosition).getNumber());
int onlineBg = ResourcesCompat.getColor(mActivity.getResources(), R.color.onlineBg, null);
int offlineBg = ResourcesCompat.getColor(mActivity.getResources(), R.color.offlineBg, null);
int white = ResourcesCompat.getColor(mActivity.getResources(), R.color.colorWhite, null);
int black = ResourcesCompat.getColor(mActivity.getResources(), R.color.colorBlack, null);
ImageView btnGetCSV = pView.findViewById(R.id.btnGetCSV);
ImageView btnNotificationOff = pView.findViewById(R.id.btnNotificationOff);
ImageView btnNotificationOn = pView.findViewById(R.id.btnNotificationOn);
ImageView btnNumberDetails = pView.findViewById(R.id.btnNumberDetails);
ImageView btnRemoveNumber = pView.findViewById(R.id.btnRemoveNumber);
btnGetCSV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onMenuItemClickListener.onGetCSVClick();
}
});
btnNotificationOff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onMenuItemClickListener.onNotificationOffClick();
}
});
btnNotificationOn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onMenuItemClickListener.onNotificationOnClick();
}
});
btnNumberDetails.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onMenuItemClickListener.onNumberDetailsClick();
}
});
btnRemoveNumber.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onMenuItemClickListener.onRemoveNumberClick();
}
});
TextView txtSatus = pView.findViewById(R.id.txt_status);
txtSatus.setText(mData.get(pPosition).isOnline() ? "Online" : "Offline");
if(mData.get(pPosition).isOnline()){
txtCount.setCompoundDrawablesWithIntrinsicBounds(drawableOnline,null,null,null);
}else{
txtCount.setCompoundDrawablesWithIntrinsicBounds(drawableOffline,null,null,null);
}
txtCount.setTextColor(mData.get(pPosition).isOnline() ? white : black);
txtCount.setBackgroundColor(mData.get(pPosition).isOnline() ? onlineBg : offlineBg);
TextView txtTime = pView.findViewById(R.id.txt_time);
txtTime.setText("Since " + mData.get(pPosition).getLastOnline());
return pView;
}
public void setData(ArrayList<Stat> data) {
mData.clear();
mData.addAll(data);
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
notifyDataSetChanged();
}
});
}
public void addData(Stat data) {
mData.add(data);
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
notifyDataSetChanged();
}
});
}
public void clearData() {
mData.clear();
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
notifyDataSetChanged();
}
});
}
public Stat getStat(int position) {
return mData.get(position);
}
public interface OnMenuItemClickListener
{
void onGetCSVClick();
void onNotificationOffClick();
void onNotificationOnClick();
void onNumberDetailsClick();
void onRemoveNumberClick();
}
}
现在你需要在适配器类的构造函数中传递“this”,这样就需要将接口的所有回调方法覆盖到片段中,然后将click事件转换为片段。
public class StateFragment extends Fragment implements StatAdapter.OnMenuItemClickListener {
private final int PERMISSION_CONTACT = 10003;
private final int PICK_CONTACT = 10;
@BindView(R.id.list_stats)
ListView mStatList;
@BindView(R.id.swipe_refresh)
SwipeRefreshLayout swipeRefresh;
EditText edtName, edtNumber;
private Activity mActivity;
private StatAdapter mAdapter;
private Dialog mWaitDialog;
ApiInterface apiService;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_stats, container, false);
mActivity = getActivity();
apiService = ApiUtils.getAPIService(getContext());
ButterKnife.bind(this, view);
NumberData.getInstance();
mAdapter = new StatAdapter(mActivity, new ArrayList<String>(),this);
mStatList.setAdapter(mAdapter);
mStatList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Stat stat = mAdapter.getStat(position);
Intent intent = new Intent(mActivity, DetailLogActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable(DetailLogActivity.DATA_OBJ, stat);
bundle.putInt("position", position);
intent.putExtras(bundle);
startActivity(intent);
}
});
swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
refreshData();
}
});
mWaitDialog = new Dialog(mActivity);
mWaitDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mWaitDialog.setContentView(R.layout.dialog_wait);
if (mWaitDialog.getWindow() != null) {
mWaitDialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
}
mWaitDialog.setCancelable(false);
retu以上是关于适配器项目单击“从片段”的主要内容,如果未能解决你的问题,请参考以下文章
从片段中获取意图值后,我如何在 recyclerview 项目中实现单击