gpt4 book ai didi

android - 如何在MainActivity中滑动viewpager时更新viewpager fragment 内容

转载 作者:行者123 更新时间:2023-11-29 01:18:20 26 4
gpt4 key购买 nike

当 viewpager 在 MainActivity 中滑动时,我正在尝试更新 viewpager fregment。

菜单 Activity :-

package jbit.kanha;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
import com.romainpiel.shimmer.Shimmer;
import com.romainpiel.shimmer.ShimmerTextView;

import org.json.JSONArray;
import org.json.JSONObject;

import jbit.kanha.AllAdepters.SideMenuAdapter;
import jbit.kanha.InternetConection.CheckInternetConection;
import jbit.kanha.InternetConection.ConnectionDetector;
import jbit.kanha.InternetConection.InternetDialoge;
import jbit.kanha.ProgressDialog.MyProgressDialog;
import jbit.kanha.SideMenuClasses.MyProfile;
import jbit.kanha.db.Database;

public class MenuActivity extends FragmentActivity implements View.OnClickListener{

public static ResideMenu resideMenu;
private MenuActivity mContext;
private ResideMenuItem itemHome;
private ResideMenuItem itemProfile;
private ResideMenuItem itemCalendar;
private ResideMenuItem itemSettings;
SharedPreferences loginPreferences;
private SharedPreferences pref;
ImageView profile_image;
public static TextView title_bar_right_menu,txt_total_rate;
Database database;
JSONArray categoryItem;
// private PagerSlidingTabStrip tabLayout;
private TabLayout tabLayout;
ViewPager pager;
private ConnectionDetector connectionDetector;
private MyProgressDialog dialog;
ViewPagerAdapter adapter;

OneFregment fregment;
// private int currentColor = Color.parseColor("#1D569B");
// PagerSlidingTabStrip tabStrip;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mContext = this;
database = new Database(MenuActivity.this);
tabLayout= (TabLayout)findViewById(R.id.tabs);

pager = (ViewPager)findViewById(R.id.pager);
loginPreferences = getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
connectionDetector = new ConnectionDetector(mContext);
dialog = new MyProgressDialog(mContext);
adapter = new ViewPagerAdapter(getSupportFragmentManager());
if (connectionDetector.isConnectingToInternet()){
getCategoryName();
}else{
Toast.makeText(mContext, "No Internet Connection", Toast.LENGTH_SHORT).show();
}
title_bar_right_menu = (TextView) findViewById(R.id.title_bar_right_menu);
txt_total_rate = (TextView) findViewById(R.id.txt_total_rate);

pref = getApplicationContext().getSharedPreferences("loginPrefs", MODE_PRIVATE);
Cursor cursor1 = database.getData("SELECT * FROM cart");
int count = cursor1.getCount();
cursor1.close();
title_bar_right_menu.setText(count+"");

setUpMenu();


pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

}

@Override
public void onPageSelected(int position) {
getCategoryDataRefresh(position);

}

@Override
public void onPageScrollStateChanged(int state) {

}
});

}


private void getCategoryData(final int postion){
Ion.with(mContext)
.load(getResources().getString(R.string.api_main_url) + "categoryoriginal.php")
.setTimeout(30*1000)
.setBodyParameter("outlet_id",loginPreferences.getString("outlet_id",""))
.setBodyParameter("catid",String.valueOf(postion+1))
.asString().setCallback(new FutureCallback<String>() {
@Override
public void onCompleted(Exception e, String result) {
dialog.hide();
if (e != null) {
e.printStackTrace();
DialogsClassTwoData(mContext, "Connection Timed Out!", "Message...",postion).show();
}
if (result != null) {
try {
Log.d("name",result);
JSONObject mainJson = new JSONObject(result);
String status = mainJson.getString("status");
if(status.equals("Success")){
JSONArray jsonArray = mainJson.getJSONArray("data");
setUpViewPager(pager,categoryItem,jsonArray);
}
}catch (Exception ex) {
ex.printStackTrace();
Log.d("exaption", ex.toString());

}
} else {
Log.d("exaption", e.toString());
}
}
});

}
private void getCategoryDataRefresh(final int postion){
dialog.show();
Ion.with(mContext)
.load(getResources().getString(R.string.api_main_url) + "categoryoriginal.php")
.setTimeout(30*1000)
.setBodyParameter("outlet_id",loginPreferences.getString("outlet_id",""))
.setBodyParameter("catid",String.valueOf(postion+1))
.asString().setCallback(new FutureCallback<String>() {
@Override
public void onCompleted(Exception e, String result) {
dialog.hide();
if (e != null) {
e.printStackTrace();
DialogsClassTwoData(mContext, "Connection Timed Out!", "Message...",postion).show();
}
if (result != null) {
try {
Log.d("name",result);
JSONObject mainJson = new JSONObject(result);
String status = mainJson.getString("status");
if(status.equals("Success")){

Fragment frg = null;
frg = new OneFregment(mainJson.getJSONArray("data"));
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();
}
}catch (Exception ex) {
ex.printStackTrace();
Log.d("exaption", ex.toString());

}
} else {
Log.d("exaption", e.toString());
}
}
});

}

private void getCategoryName(){
dialog.show();
Ion.with(mContext)
.load(getResources().getString(R.string.api_main_url) + "categoryname.php")
.setTimeout(30*1000)
.asString().setCallback(new FutureCallback<String>() {
@Override
public void onCompleted(Exception e, String result) {
// dialog.hide();
if (e != null) {
e.printStackTrace();
DialogsClassTwo(mContext, "Connection Timed Out!", "Message...").show();
}
if (result != null) {
try {
Log.d("name",result);
JSONObject mainJson = new JSONObject(result);
String status = mainJson.getString("status");
if(status.equals("Success")){
JSONObject jsonObject = mainJson.getJSONObject("data");
categoryItem = jsonObject.getJSONArray("items");

// setUpViewPager(pager,jsonObject.getJSONArray("items"));
Log.d("json",jsonObject+"");

getCategoryData(0);
//data = jsonObject.getJSONArray("items");
/* for(int i=0;i<data.length();i++){
JSONObject jsonObject1 = data.getJSONObject(i);
bigImage.add(jsonObject1.getString("bigimage"));
}
pager.setAdapter(new CustomPagerAdapter(getActivity(),data));
final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
.getDisplayMetrics());
pager.setPageMargin(pageMargin);
tabs.setViewPager(pager);
changeColor(currentColor);*/

}
}catch (Exception ex) {
ex.printStackTrace();
Log.d("exaption", ex.toString());

}
} else {
Log.d("exaption", e.toString());
}
}
});
}
private void setUpViewPager(ViewPager pager, JSONArray jsonArray,JSONArray products){
try {
// ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
adapter.addFrag(new OneFregment(products),jsonObject.getString("categoryname"));
}
pager.setAdapter(adapter);
tabLayout.setupWithViewPager(pager);
// tabLayout.tabSelectedTextColor
// getCategoryData();
}
catch (Exception e) {
Log.e("error", e.getMessage());
}
}

public AlertDialog.Builder DialogsClassTwo(Context cxt, final String message, String title){
return new AlertDialog.Builder(cxt).setTitle(title).setMessage(message).setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogs, int which) {
// here you can add functions
if (CheckInternetConection.isInternetConnection(mContext.getApplicationContext())){
getCategoryName();
// getCategoryData();
}else{
InternetDialoge.showDialogFinishActivity(
"Internet Connection Failed!", "connection error", mContext);
}
}
});
}
public AlertDialog.Builder DialogsClassTwoData(Context cxt, final String message, String title, final int postion){
return new AlertDialog.Builder(cxt).setTitle(title).setMessage(message).setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogs, int which) {
// here you can add functions
if (CheckInternetConection.isInternetConnection(mContext.getApplicationContext())){
//getCategoryName();
getCategoryData(postion);
}else{
InternetDialoge.showDialogFinishActivity(
"Internet Connection Failed!", "connection error", mContext);
}
}
});
}

private void setUpMenu() {
resideMenu = new ResideMenu(MenuActivity.this, R.layout.side_menu, R.layout.home);
//resideMenu.setBackground(Color.parseColor("#FAA514"));//FAA514
resideMenu.setBackground(R.drawable.slider_background);
resideMenu.attachToActivity(MenuActivity.this);
resideMenu.setScaleValue(0.5f);
View leftMenu = resideMenu.getLeftMenuView();
Shimmer shimmer = new Shimmer();//#faebd7
shimmer.setDuration(3000)
.setStartDelay(500)
.setDirection(Shimmer.ANIMATION_DIRECTION_LTR);
ShimmerTextView powered = (ShimmerTextView)leftMenu.findViewById(R.id.powered);
ListView list = (ListView) leftMenu.findViewById(R.id.list1);
list.setAdapter(new SideMenuAdapter(MenuActivity.this));
profile_image = (ImageView) leftMenu.findViewById(R.id.profile_image);
TextView title1 = (TextView) leftMenu.findViewById(R.id.title1);
TextView loction1 = (TextView) leftMenu.findViewById(R.id.loction1);
ImageView location_icon =(ImageView) leftMenu.findViewById(R.id.location_icon);
RelativeLayout ll_checkout = (RelativeLayout) findViewById(R.id.ll_checkout);
//loginPreferences = getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
title1.setText(loginPreferences.getString("fullname",""));
loction1.setText(loginPreferences.getString("address",""));
// if(!loginPreferences.getString("profileimage","").equals("")){
/* Picasso.with(MenuActivity.this)
.load(loginPreferences.getString("profileimage",""))
.error(R.drawable.images)
.placeholder(R.drawable.progress_animation)
.into(profile_image);*/
// File file = new File("/main_json/main_json/com.example.w.lazymojo/app_imageDir/profile.jpg");

shimmer.start(powered);
if(pref.getString("User_id", "").equals("")){
profile_image.setImageResource(R.drawable.images);
location_icon.setVisibility(View.INVISIBLE);
}
else {
Bitmap bitmap1 = BitmapFactory.decodeFile("/data/data/jbit.kanha/app_imageDir/profile.jpg");
if(bitmap1!=null){
Log.d("MenuActivity:-","image not null");
profile_image.setImageBitmap(bitmap1);
// Picasso.with(MenuActivity.this).load(file).resize(dpToPx(96),dpToPx(96)).centerCrop().into(profile_image);
}
else {
Log.d("MenuActivity:-","image is null");
profile_image.setImageResource(R.drawable.images);
}
}

profile_image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(pref.getString("User_id", "").equals("")){
profile_image.setImageResource(R.drawable.images);
new AlertDialog.Builder(MenuActivity.this).setTitle("Login").setMessage("You have to login first").setPositiveButton("Login", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent in = new Intent(MenuActivity.this,LoginActivity.class);
startActivity(in);
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
else {
Intent i = new Intent(MenuActivity.this, MyProfile.class);
startActivity(i);
}
}
});

// }
ll_checkout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!pref.getString("User_id", "").equals("")){
Intent i = new Intent(MenuActivity.this,MyCart.class);
startActivity(i);
finish();
}
else
{
new AlertDialog.Builder(MenuActivity.this).setTitle("Login").setMessage("You must login first").setPositiveButton("Login", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(MenuActivity.this,LoginActivity.class);
startActivity(intent);
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
}
});
resideMenu.setSwipeDirectionDisable(ResideMenu.DIRECTION_RIGHT);
resideMenu.setSwipeDirectionDisable(ResideMenu.DIRECTION_LEFT);
findViewById(R.id.title_bar_left_menu).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
resideMenu.openMenu(ResideMenu.DIRECTION_LEFT);
}
});
findViewById(R.id.cart_img).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!pref.getString("User_id", "").equals("")){
Intent i = new Intent(MenuActivity.this,MyCart.class);
startActivity(i);
finish();
}
else
{
new AlertDialog.Builder(MenuActivity.this).setTitle("Login").setMessage("You must login first").setPositiveButton("Login", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(MenuActivity.this,LoginActivity.class);
startActivity(intent);
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
// resideMenu.openMenu(ResideMenu.DIRECTION_RIGHT);
}
});
}


@Override
public void onClick(View view) {
resideMenu.closeMenu();
}

private ResideMenu.OnMenuListener menuListener = new ResideMenu.OnMenuListener() {
@Override
public void openMenu() {
// Toast.makeText(mContext, "Menu is opened!", Toast.LENGTH_SHORT).show();
}

@Override
public void closeMenu() {
//Toast.makeText(mContext, "Menu is closed!", Toast.LENGTH_SHORT).show();
}
};

// What good method is to access resideMenu?
public ResideMenu getResideMenu(){
return resideMenu;
}


@Override
protected void onResume() {
super.onResume();
}

@Override
public void onBackPressed() {
super.onBackPressed();
finish();
moveTaskToBack(true);
}
}

ViewPagerAdapter.java:

class  ViewPagerAdapter extends FragmentPagerAdapter {

private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();

public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}

@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}

@Override
public int getCount() {
return mFragmentList.size();
}

public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}

@Override
public int getItemPosition(Object object) {

return POSITION_NONE;
}

@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}

OneFregement:-

public class OneFregment extends Fragment {


JSONArray jsonArray;
ListView listView;
HomeLiatAdapter adapter;

public OneFregment() {
// Required empty public constructor
}

@SuppressLint("ValidFragment")
public OneFregment(JSONArray jsonArray){
this.jsonArray = jsonArray;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.home_child_layout, container, false);

listView = (ListView) v.findViewById(R.id.list);

try {
JSONObject obj = jsonArray.getJSONObject(0);
adapter = new HomeLiatAdapter(getContext(),obj.getJSONArray("items"),obj.getString("bigimage"));
listView.setAdapter(adapter);

}catch (Exception e){
e.printStackTrace();
}


return v;
}

/* public void update(){
try {
JSONObject obj = jsonArray.getJSONObject(0);
adapter = new HomeLiatAdapter(getContext(),obj.getJSONArray("items"),obj.getString("bigimage"));
listView.setAdapter(adapter);

}catch (Exception e){
e.printStackTrace();
}
}*/
}

我正在这样做,但 fregment 显示以前的数据。我也尝试在 fregment 类中创建更新方法,但一切都在等待。

我是 Android 开发的新手,请帮助我。提前致谢。

最佳答案

您必须编写自定义接口(interface)并在每个 fragment 中实现。在 onpagechangelistener 上,您必须调用这些方法。

check this更多解释。甚至我必须为我的项目实现相同的操作以使 fragment 更新,因为正常的 fragment 生命周期不会按您想要的那样工作。由于在您滑动浏览时查看寻呼机添加和保留 fragment 。

关于android - 如何在MainActivity中滑动viewpager时更新viewpager fragment 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38342761/

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