[英]Issue when pass data from activity to fragment
This is my original app: 这是我的原始应用程序:
When i click button to pass data from activity to fragment my app become in this way: 当我单击按钮以将数据从活动传递到片段时,我的应用程序将以这种方式变为:
I don't know why! 我不知道为什么!
I show you my code! 我给你看我的代码!
ACTIVITY_SCROLLABLE_TABS.XML: ACTIVITY_SCROLLABLE_TABS.XML:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/container">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:gravity="center"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/welcome"
android:textSize="20dp"
android:layout_marginLeft="5dp"
/>
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:textColor="@color/lbl_name"
android:textSize="24dp"
android:layout_marginLeft="5dp"
/>
<Button
android:id="@+id/btnLogout"
android:layout_width="122dp"
android:layout_height="wrap_content"
android:layout_marginRight="40dip"
android:background="@color/btn_logut_bg"
android:text="@string/btn_logout"
android:textAllCaps="false"
android:textColor="@color/white"
android:textSize="15dp"
android:layout_marginLeft="5dp"
android:onClick="logoutUser"
/>
</LinearLayout>
<!-- <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/azz"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>-->
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" >
<!-- <fragment
android:id="@+id/details_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>-->
</android.support.v4.view.ViewPager>
</android.support.design.widget.CoordinatorLayout>
ACTIVITY: 活动:
public class ScrollableTabsActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private Button cazzo;
//private SQLiteHandler db;
private SessionManager session;
private TextView txtName;
private TextView txtEmail;
int s;
String intentt="";
File file;
Uri filePath;
ArrayList<Integer> hm=new ArrayList<>();
String path;
ArrayList<Planet> planetList=new ArrayList();
private String myString = "azz";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scrollable_tabs);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
cazzo = (Button) findViewById(R.id.btnLogout);
txtName = (TextView) findViewById(R.id.name);
txtEmail = (TextView) findViewById(R.id.numero_telefonico);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
cazzo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
logoutUser();
}
});
//db = new SQLiteHandler(getApplication());
// session manager
/* session = new SessionManager(getApplication());
if (!session.isLoggedIn()) {
logoutUser();
}*/
// Fetching user details from SQLite
/* HashMap<String, String> user = db.getUserDetails();
String name = user.get("name");
String email = user.get("email");
String id=user.get("id");
// Displaying the user details on the screen
System.out.println(name + email);
txtName.setText(email);*/
s = getIntent().getIntExtra("EXTRA_SESSION_ID",0);
System.out.println("IDDDDDDD" + s);
// getMyData();
}
/* public int getMyData() {
return s;
}*/
private void logoutUser() {
//session.setLogin(false);
// db.deleteUsers();
// Launching the login activity
/* Intent intent = new Intent(ScrollableTabsActivity.this, LoginActivity.class);
startActivity(intent);
finish();*/
Intent intent = new Intent();
intent.setPackage("com.asus.filemanager");
intent.setType("text/xml");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "LOGOUT"), 1);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
filePath = data.getData();
path = FilePath.getPath(this, filePath);
System.out.println("PATH" + path);
int a=0;
String status="";
boolean statuss = false;
String intenttt= path;
System.out.println("INTENT:"+intenttt);
file = new File(intenttt);
System.out.println("FILE:"+file);
FileInputStream is = null;
try {
is = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = null;
try {
dBuilder = dbFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
Document doc = null;
try {
doc = dBuilder.parse(is);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Element element = doc.getDocumentElement();
element.normalize();
NodeList nList = doc.getElementsByTagName("checkboxes_pizza");
for (int i = 0; i < nList.getLength(); i++) {
Node node = nList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element2 = (Element) node;
//tv1.setText(tv1.getText()+"\nName : " + getValue("name", element2)+"\n");
String id = getValue("id", element2);
a = Integer.parseInt(id);
status = getValue("status", element2);
statuss= Boolean.parseBoolean(status);
System.out.println("XML:" + a);
hm.add(a);
System.out.println("AZZ:" + hm);
}
}
//getMyData();
Bundle bundle = new Bundle();
bundle.putString("params", "My String data");
/* MyListFragment myObj = new MyListFragment();
myObj.setArguments(bundle);*/
Fragment fragment = new MyListFragment();
fragment.setArguments(bundle);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.container, fragment);
transaction.commit();
System.out.println("PASSATO "+bundle);
}
private static String getValue(String tag, Element element) {
NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = nodeList.item(0);
return node.getNodeValue();
}
/* @Override
protected void onPause() {
super.onPause();
logoutUser();
}*/
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new MyListFragment(), "PIZZE");
adapter.addFrag(new SixFragment(), "SIX");
adapter.addFrag(new FiveFragment(), "TAVOLI");
adapter.addFrag(new ThreeFragment(), "BEVANDE");
adapter.addFrag(new FourFragment(), "STAMPA");
adapter.addFrag(new TwoFragment(), "TWO");
adapter.addFrag(new SevenFragment(), "SEVEN");
adapter.addFrag(new EightFragment(), "EIGHT");
adapter.addFrag(new NineFragment(), "NINE");
adapter.addFrag(new TenFragment(), "TEN");
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(10);
}
/*private void logoutUser() {
SessionManager session;
session.setLogin(false);
db.deleteUsers();
// Launching the login activity
// Intent intent = new Intent(MyListFragment.this, LoginActivity.class);
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
getA.finish();
}*/
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 CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
PLANET ADAPTER: 行星适配器:
public class PlanetAdapter extends ArrayAdapter<Planet> implements CompoundButton.OnCheckedChangeListener, View.OnClickListener
{
private List<Planet> planetList;
private Context context ;
ArrayList<Birra> objects;
public boolean Checked;
private Integer[] imageId;
String ciao;
static PlanetAdapter plAdapter;
String selState ;
boolean[] itemChecked;
ArrayList<Integer> hmmm;
//MyListner mListener;
public PlanetAdapter(List<Planet> planetList, Context context,Integer[] imageId,ArrayList<Integer> hm) {
super(context, R.layout.single_listview_item,planetList);
//itemChecked = new boolean[planetList.size()];
this.planetList = planetList;
this.context = context;
this.imageId = imageId;
this.itemChecked=new boolean[planetList.size()];
this.hmmm=hm;
// mListener=(MyListner)context;
}
public PlanetAdapter(@NonNull Context context, @LayoutRes int resource,ArrayList<Integer> a) {
super(context, resource);
this.hmmm=a;
System.out.println("ARRAYLIST2:"+hmmm);
}
/* public void setItems(ArrayList<Integer> items) {
hmmm = items;
notifyDataSetChanged();
//System.out.println("HMMM:"+hmmm);
}*/
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
@Override
public void onClick(View v) {
}
public class PlanetHolder {
public TextView planetName;
public TextView distView;
public TextView valuta;
public CheckBox chkBox;
// public EditText edit;
public TextView caratteristica;
public TextView id;
public ImageView imageView;
public Spinner spinner;
public NumberPicker np;
}
@Override
public int getCount() {
return planetList.size();
}
@Override
public Planet getItem(int position) {
return planetList.get(position);
}
// static ArrayList<Integer> itemss;
@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
View row = convertView;
PlanetHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(R.layout.single_listview_item, parent, false);
holder = new PlanetHolder();
holder.planetName = (TextView) row.findViewById(R.id.name);
holder.distView = (TextView) row.findViewById(R.id.dist);
holder.valuta = (TextView) row.findViewById(R.id.valuta);
holder.chkBox = (CheckBox) row.findViewById(R.id.chk_box);
holder.spinner = (Spinner) row.findViewById(R.id.simpleSpinner);
holder.np=(NumberPicker)row.findViewById(R.id.np);
// iterator.setOnClickListener(this.PlanetHolder);
holder.caratteristica=(TextView) row.findViewById(R.id.caratteristica);
holder.imageView = (ImageView) row.findViewById(R.id.ivImage);
holder.spinner.setVisibility(View.GONE);
// holder.id = (TextView) row.findViewById(R.id.id);
row.setTag(holder);
} else {
holder = (PlanetHolder) row.getTag();
}
final Planet p = planetList.get(position);
System.out.println("stampato P" + p);
holder.imageView.setImageResource(imageId[position]);
holder.planetName.setText(p.getName());
holder.distView.setText("" + p.getDistance());
holder.valuta.setText("" + p.getValuta());
holder.chkBox.setChecked(p.isSelected());
holder.chkBox.setTag(p);
holder.caratteristica.setText(p.getCaratteristica());
SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
boolean isChecked = states.getBoolean("holder.chkBox" + holder.planetName.getText().toString(), false);
System.out.println(isChecked);
if (isChecked) {
holder.spinner.setVisibility(View.VISIBLE);
holder.np.setVisibility(View.VISIBLE);
} else {
holder.chkBox.setChecked(false);
holder.spinner.setVisibility(View.GONE);
holder.np.setVisibility(View.GONE);
}
holder.chkBox.setOnCheckedChangeListener(PlanetAdapter.this);
final PlanetHolder finalHolder = holder;
Planet z=getItem(position);
System.out.println(z);
holder.chkBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
if (finalHolder.chkBox.isChecked()) {
itemChecked[position]=true;
System.out.println("POSITION:"+position);
finalHolder.spinner.setVisibility(View.VISIBLE);
finalHolder.np.setVisibility(View.VISIBLE);
finalHolder.np.setMaxValue(10);
finalHolder.np.setMinValue(0);
finalHolder.np.setWrapSelectorWheel(true);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
getContext(),
R.array.country_arrays,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
finalHolder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
finalHolder.spinner.setSelection(position);
// selState = finalHolder.spinner.getSelectedItem().toString();
// p.setQuantità(finalHolder.edit.getText().toString().trim());
p.setTipo(finalHolder.spinner.getSelectedItem().toString());
System.out.println("p.getTipo()"+p.getTipo());
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
finalHolder.np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
p.setQuantità2(newVal);
System.out.println(p.getQuantità2());
SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = states.edit();
editor.putInt("finalHolder.picker" + finalHolder.planetName.getText().toString(), finalHolder.np.getId());
editor.commit();
}
});
SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = states.edit();
editor.putBoolean("holder.chkBox" + finalHolder.planetName.getText().toString(), true);
editor.commit();
} else {
finalHolder.spinner.setVisibility(View.GONE);
finalHolder.np.setVisibility(View.GONE);
finalHolder.np.setValue(0);
}
}
});
return row;
}
}
SINGLE_LISTVIEW_ITEM.XML SINGLE_LISTVIEW_ITEM.XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<CheckBox
android:id="@+id/chk_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true" />
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:orientation="vertical"
android:layout_weight="1" >
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/chk_box"
android:textStyle="bold"
android:textColor="#000000" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/caratteristica"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/name"
android:layout_toRightOf="@id/chk_box"
android:textStyle="italic" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/dist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/caratteristica"
android:layout_toRightOf="@id/chk_box"
android:textSize="12sp"
android:textStyle="italic" />
<TextView
android:id="@+id/valuta"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:textSize="12sp"
android:textStyle="italic" />
</LinearLayout>
<Spinner
android:id="@+id/simpleSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:entries="@array/country_arrays"/>
<NumberPicker
android:id="@+id/np"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
<ImageView
android:id="@+id/ivImage"
android:layout_width="72dp"
android:layout_height="72dp"
android:layout_marginRight="5dp"
android:layout_gravity="center"
/>
</LinearLayout>
Please format your code and remove excessive empty lines. 请格式化您的代码并删除多余的空行。 Because it's almost unreadable
因为它几乎不可读
Don't add the Fragment in onActivityResult
but in onCreate
and set adapter data in onActivityResult if necessary. 不要在
onActivityResult
添加片段,而在onCreate
添加片段,并在必要时在onActivityResult中设置适配器数据。
So move this code in onCreate
: 因此,将这段代码移到
onCreate
:
Fragment fragment = new MyListFragment();
fragment.setArguments(bundle);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.container, fragment);
transaction.commit();
And MyListFragment
should have a method called refreshlist
而且
MyListFragment
应该有一个称为refreshlist
的方法
Also, in the fragment layout, put a background white in xml: 另外,在片段布局中,在xml中放置白色背景:
android:background="@android:color/white"
Problem occurs when your hide and show Spinner
and NumberPicker
from adapter's getView()
method: 当您从适配器的
getView()
方法隐藏并显示Spinner
和NumberPicker
时,会发生问题:
@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
........
................
if (isChecked) {
holder.spinner.setVisibility(View.VISIBLE);
holder.np.setVisibility(View.VISIBLE);
} else {
holder.chkBox.setChecked(false);
holder.spinner.setVisibility(View.GONE);
holder.np.setVisibility(View.GONE);
}
........
................
}
Seems your layout design for Listview
item is not OK. 似乎您的
Listview
项的布局设计不正确。 Update your single_listview_item.xml
layout design as below: 如下更新您的
single_listview_item.xml
布局设计:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<CheckBox
android:id="@+id/chk_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true" />
<ImageView
android:id="@+id/ivImage"
android:layout_width="72dp"
android:layout_height="72dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"/>
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_toRightOf="@id/chk_box"
android:layout_toLeftOf="@id/ivImage"
android:orientation="vertical">
<TextView
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/chk_box"
android:textStyle="bold"
android:textColor="#000000"
android:text="This ia name"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/caratteristica"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/name"
android:layout_toRightOf="@id/chk_box"
android:textStyle="italic"
android:text="This is caratteristica"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/dist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:textStyle="italic"
android:text="10"/>
<TextView
android:id="@+id/valuta"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:textSize="12sp"
android:textStyle="italic"
android:text="$"/>
</LinearLayout>
<Spinner
android:id="@+id/simpleSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:entries="@array/country_arrays"
android:visibility="visible"/>
<NumberPicker
android:id="@+id/np"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible"/>
</LinearLayout>
</RelativeLayout>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.