我想我实现的微调器选择不当。
所以我从数据库中加载了微调器值。我正试图根据所选微调器加载数据,但微调器不会持久化,id也不会传递给活动。它加载的默认id是1,而不是所选的微调器id。因此我不确定是否传递了微调器id。如何检查和纠正这些问题?
package com.example.app;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.firebase.messaging.FirebaseMessaging;
import com.example.app.Config;
import com.example.app.R;
import com.example.app.fragment.FragmentCategory;
import com.example.app.fragment.FragmentFavorite;
import com.example.app.fragment.FragmentProfile;
import com.example.app.fragment.FragmentRecent;
import com.example.app.fragment.FragmentVideo;
import com.example.app.models.Constituency;
import com.example.app.utils.AppBarLayoutBehavior;
import com.example.app.utils.Constant;
import com.example.app.utils.GDPR;
import com.squareup.picasso.Picasso;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
public class MainActivity extends AppCompatActivity {
String URL="https://xxx.xxx.xxx/api/get_constituency_index/?api_key="+
Config.API_KEY;
private long exitTime = 0;
MyApplication myApplication;
View view;
private BottomNavigationView navigation;
public ViewPager viewPager;
private Toolbar toolbar;
MenuItem prevMenuItem;
int pager_number = 5;
BroadcastReceiver broadcastReceiver;
Spinner mySpinner;
ArrayList<String> spinnerConstituencyName;
int spinConstID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set Font
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/Arkhip_font.ttf")
.setFontAttrId(R.attr.fontPath)
.build());
setContentView(R.layout.activity_main);
view = findViewById(android.R.id.content);
if (Config.ENABLE_RTL_MODE) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
}
}
AppBarLayout appBarLayout = findViewById(R.id.tab_appbar_layout);
((CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams()).setBehavior(new AppBarLayoutBehavior());
myApplication = MyApplication.getInstance();
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(R.string.app_name);
spinnerConstituencyName = new ArrayList<>();
mySpinner = findViewById(R.id.mySpinner);
loadSpinnerData(URL);
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
int check = 0;
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
/*String spinConstituency = mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()).toString();
Toast.makeText(getApplicationContext(), spinConstituency, Toast.LENGTH_LONG).show();*/
if ( ++check > 1 ){
PrefManager prefManager = new PrefManager(MainActivity.this);
prefManager.writeString("" + spinConstID);
Intent intent = getIntent();
startActivity(intent);
Toast.makeText(getApplicationContext(), mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()).toString() + " Showing", Toast.LENGTH_SHORT).show();
finish();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
viewPager.setOffscreenPageLimit(pager_number);
navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
viewPager.setCurrentItem(0);
return true;
case R.id.navigation_category:
viewPager.setCurrentItem(1);
return true;
case R.id.navigation_video:
viewPager.setCurrentItem(2);
return true;
case R.id.navigation_favorite:
viewPager.setCurrentItem(3);
return true;
case R.id.navigation_profile:
viewPager.setCurrentItem(4);
return true;
}
return false;
}
});
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
if (prevMenuItem != null) {
prevMenuItem.setChecked(false);
} else {
navigation.getMenu().getItem(0).setChecked(false);
}
navigation.getMenu().getItem(position).setChecked(true);
prevMenuItem = navigation.getMenu().getItem(position);
if (viewPager.getCurrentItem() == 1) {
toolbar.setTitle(getResources().getString(R.string.title_nav_category));
} else if (viewPager.getCurrentItem() == 2) {
toolbar.setTitle(getResources().getString(R.string.title_nav_video));
} else if (viewPager.getCurrentItem() == 3) {
toolbar.setTitle(getResources().getString(R.string.title_nav_favorite));
} else if (viewPager.getCurrentItem() == 4) {
toolbar.setTitle(getResources().getString(R.string.title_nav_favorite));
} else {
toolbar.setTitle(R.string.app_name);
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
if (Config.ENABLE_RTL_MODE) {
viewPager.setRotationY(180);
}
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// checking for type intent filter
if (intent.getAction().equals(Constant.REGISTRATION_COMPLETE)) {
// now subscribe to global topic to receive app wide notifications
FirebaseMessaging.getInstance().subscribeToTopic(Constant.TOPIC_GLOBAL);
} else if (intent.getAction().equals(Constant.PUSH_NOTIFICATION)) {
// new push notification is received
String message = intent.getStringExtra("message");
Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show();
}
}
};
Intent intent = getIntent();
final String message = intent.getStringExtra("message");
final String imageUrl = intent.getStringExtra("image");
final long nid = intent.getLongExtra("id", 0);
final String link = intent.getStringExtra("link");
if (message != null) {
LayoutInflater layoutInflaterAndroid = LayoutInflater.from(MainActivity.this);
View mView = layoutInflaterAndroid.inflate(R.layout.custom_dialog_notif, null);
final AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setView(mView);
final TextView notification_title = mView.findViewById(R.id.news_title);
final TextView notification_message = mView.findViewById(R.id.news_message);
final ImageView notification_image = mView.findViewById(R.id.news_image);
if (imageUrl.endsWith(".jpg") || imageUrl.endsWith(".jpeg") || imageUrl.endsWith(".png") || imageUrl.endsWith(".gif")) {
notification_title.setText(message);
notification_message.setVisibility(View.GONE);
Picasso.with(MainActivity.this)
.load(imageUrl.replace(" ", "%20"))
.placeholder(R.drawable.ic_thumbnail)
.resize(200, 200)
.centerCrop()
.into(notification_image);
alert.setPositiveButton(R.string.dialog_read_more, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), ActivityNotificationDetail.class);
intent.putExtra("id", nid);
startActivity(intent);
}
});
alert.setNegativeButton(R.string.dialog_dismiss, null);
} else {
notification_title.setText(getResources().getString(R.string.app_name));
notification_message.setVisibility(View.VISIBLE);
notification_message.setText(message);
notification_image.setVisibility(View.GONE);
//Toast.makeText(getApplicationContext(), "link : " + link, Toast.LENGTH_SHORT).show();
if (!link.equals("")) {
alert.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent open = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
startActivity(open);
}
});
alert.setNegativeButton(R.string.dialog_dismiss, null);
} else {
alert.setPositiveButton(R.string.dialog_ok, null);
}
}
alert.setCancelable(false);
alert.show();
}
GDPR.updateConsentStatus(this);
}
public class MyAdapter extends FragmentPagerAdapter {
private MyAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FragmentRecent();
case 1:
return new FragmentCategory();
case 2:
return new FragmentVideo();
case 3:
return new FragmentFavorite();
case 4:
return new FragmentProfile();
}
return null;
}
@Override
public int getCount() {
return pager_number;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.search:
Intent intent = new Intent(getApplicationContext(), ActivitySearch.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
@Override
public void onBackPressed() {
if (viewPager.getCurrentItem() != 0) {
viewPager.setCurrentItem((0), true);
} else {
exitApp();
}
}
public void exitApp() {
if ((System.currentTimeMillis() - exitTime) > 2000) {
Toast.makeText(this, getString(R.string.press_again_to_exit), Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
finish();
}
}
@Override
protected void onResume() {
super.onResume();
}
private int getIndex(Spinner spinner, String myString){
int index = 0;
for (int i=0;i<spinner.getCount();i++){
if (spinner.getItemAtPosition(i).equals(myString)){
index = i;
}
}
return index;
}
private void loadSpinnerData(String url) {
RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try{
JSONObject jsonObject=new JSONObject(response);
if(jsonObject.getString("status").equals("ok")){
JSONArray jsonArray=jsonObject.getJSONArray("constituencies");
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String spinConstituency=jsonObject1.getString("constituency_name");
spinConstID = jsonObject1.getInt("const_id");
spinnerConstituencyName.add(spinConstituency);
}
}
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(MainActivity.this,
R.layout.custom_spinner_item, spinnerConstituencyName){
@Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
View view = super.getDropDownView(position, convertView, parent);
TextView tv = (TextView) view;
if(position%2 == 1) {
// Set the item background color
tv.setBackgroundColor(Color.parseColor("#910D3F"));
}
else {
// Set the alternate item background color
tv.setBackgroundColor(Color.parseColor("#41061C"));
}
return view;
}
};
mySpinner.setPrompt("Select Your Constituency");
myAdapter.setDropDownViewResource(R.layout.custom_spinner_item);
mySpinner.setAdapter(myAdapter);
//RECEIVE DATA VIA INTENT
Intent i = getIntent();
String name = i.getStringExtra("NAME_KEY");
mySpinner.setSelection(getIndex(mySpinner, name));
}catch (JSONException e){e.printStackTrace();}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
int socketTimeout = 30000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
}
2条答案
按热度按时间d4so4syb1#
在mselectedListener内的微调器中,使用parent.getitematposition(position)获取正确的值
7fhtutme2#
下面是问题(关于微调器项选择)
**您正在以“新建”和“完成当前活动”的形式启动当前活动,这意味着当您从微调器中选择任何项时,它将启动一个新活动,并且您的“创建”操作将反复执行,因此请放置其他逻辑,或者您可以使用在活动中发送值
intent.putextra()
并在oncreate中签入null,如果值不为null,则可以设置spinner.setSelected(Your Position)
. 对于你可以使用的片段刷新你的片段,传递你的数据和bundle并检查null如果你的bundle为null,那么使用你的代码进行defalt,如果不是null,那么根据你的id设置你的数据。
**
谢谢